跳到主要内容

std::string end() 方法

// Non-const version
constexpr iterator end() noexcept;

// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;

返回指向数组末尾之后元素的迭代器

指向数组末尾之后元素的迭代器。
如果数组为空,返回的迭代器将等于 begin()

尝试解引用末尾之后的迭代器是未定义行为

.

参数

(无)

返回值

指向最后一个字符后面字符的迭代器

复杂度

常数 - O(1)

备注

对于容器c,表达式*c.begin()等效于c.front()

end 和 cend 的区别

对于 const 容器 c,end 和 cend 是相同的 - c.end() == c.cend()

对于非常量类型c的容器,它们返回不同的迭代器

#include <string>

int main()
{
std::string str = "Hello";
auto it = str.end(); // Type: std::string::iterator
*std::prev(it) = 'J'; // ✔ Ok
}

示例

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
本文源自此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了修改。点击“编辑此页面”以查看本文档所做的所有更改。
悬停查看原始许可证。

std::string end() 方法

// Non-const version
constexpr iterator end() noexcept;

// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;

返回指向数组末尾之后元素的迭代器

指向数组末尾之后元素的迭代器。
如果数组为空,返回的迭代器将等于 begin()

尝试解引用末尾之后的迭代器是未定义行为

.

参数

(无)

返回值

指向最后一个字符后面字符的迭代器

复杂度

常数 - O(1)

备注

对于容器c,表达式*c.begin()等效于c.front()

end 和 cend 的区别

对于 const 容器 c,end 和 cend 是相同的 - c.end() == c.cend()

对于非常量类型c的容器,它们返回不同的迭代器

#include <string>

int main()
{
std::string str = "Hello";
auto it = str.end(); // Type: std::string::iterator
*std::prev(it) = 'J'; // ✔ Ok
}

示例

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
本文源自此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了修改。点击“编辑此页面”以查看本文档所做的所有更改。
悬停查看原始许可证。