std::string end() 方法
- 自 C++20 起
- 自 C++11 起
- 直到 C++11
// Non-const version
constexpr iterator end() noexcept;
// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;
// Non-const version
iterator end() noexcept;
// Const version
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
// Non-const version
iterator end();
// Const version
const_iterator end() const;
返回指向数组末尾之后元素的迭代器。
指向数组末尾之后元素的迭代器。如果数组为空,返回的迭代器将等于
begin()
。
尝试解引用末尾之后的迭代器是未定义行为
.参数
(无)
返回值
指向最后一个字符后面字符的迭代器
复杂度
常数 - O(1)。
备注
对于容器c
,表达式*c.begin()
等效于c.front()
。
end 和 cend 的区别
对于 const 容器 c
,end 和 cend 是相同的 - c.end() == c.cend()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- end
- cend
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.end(); // Type: std::string::iterator
*std::prev(it) = 'J'; // ✔ Ok
}
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.cend(); // Type: std::string::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
- end
- cend
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.end(); // Type: std::string::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.cend(); // Type: std::string::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
示例
Main.cpp
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
int main()
{
std::string s("Exemparl");
std::next_permutation(s.begin(), s.end());
std::string c;
std::copy(s.cbegin(), s.cend(), std::back_inserter(c));
std::cout << c <<'\n'; // "Exemplar"
}
输出
Exemplar