跳到主要内容

std::string_view end() 方法

// Const version only
constexpr iterator end() const noexcept;

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

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

指向视图末尾之外的元素。

如果数组为空,返回的迭代器将等于 begin()

未定义行为

尝试解引用越界迭代器是未定义行为

.

参数

(无)

返回值

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

复杂度

常数 - O(1)

备注

对于容器 c,表达式 *std::prev(c.end()) 等价于 c.back()

end 和 cend 的区别

std::stringstd::vector 等其他容器不同,endcend 都返回相同的迭代器。

#include <string_view>

int main()
{
std::string_view str = "Hello";
auto it = str.cend(); // Type: std::string_view::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}

示例

Main.cpp
#include <iostream>
#include <iterator>
#include <string_view>

int main()
{
std::string_view str_view("abcd");

auto end = str_view.end();
auto cend = str_view.cend();

std::cout << *std::prev(end) << '\n';
std::cout << *std::prev(cend) << '\n';

std::cout << std::boolalpha << (end == cend) << '\n';
}
输出
d
d
true
本文源自此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了更改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string_view end() 方法

// Const version only
constexpr iterator end() const noexcept;

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

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

指向视图末尾之外的元素。

如果数组为空,返回的迭代器将等于 begin()

未定义行为

尝试解引用越界迭代器是未定义行为

.

参数

(无)

返回值

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

复杂度

常数 - O(1)

备注

对于容器 c,表达式 *std::prev(c.end()) 等价于 c.back()

end 和 cend 的区别

std::stringstd::vector 等其他容器不同,endcend 都返回相同的迭代器。

#include <string_view>

int main()
{
std::string_view str = "Hello";
auto it = str.cend(); // Type: std::string_view::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}

示例

Main.cpp
#include <iostream>
#include <iterator>
#include <string_view>

int main()
{
std::string_view str_view("abcd");

auto end = str_view.end();
auto cend = str_view.cend();

std::cout << *std::prev(end) << '\n';
std::cout << *std::prev(cend) << '\n';

std::cout << std::boolalpha << (end == cend) << '\n';
}
输出
d
d
true
本文源自此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了更改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。