std::string_view end() 方法
- 自 C++17 起
// 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::string
或 std::vector
等其他容器不同,end
和 cend
都返回相同的迭代器。
- 非常量容器
- 常量容器
- end
- cend
#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!
}
#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!
}
- end
- cend
#include <string_view>
int main()
{
const std::string_view str = "Hello";
auto it = str.end(); // Type: std::string_view::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
#include <string_view>
int main()
{
const 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