std::string_view begin()/cbegin() 方法
- 自 C++17 起
// Const version only
constexpr const_iterator begin() const noexcept;
// Const version only
constexpr const_iterator cbegin() const noexcept;
返回指向数组末尾之后元素的迭代器。
指向视图的第一个元素。如果视图为空,返回的迭代器将等于 end()
。
参数
(无)
返回值
指向第一个字符的迭代器。
复杂度
常数 - O(1)。
备注
对于容器c
,表达式*c.begin()
等效于c.front()
。
begin 和 cbegin 的区别
与其他容器(如 std::string
或 std::vector
)不同,begin
和 cbegin
都返回相同的迭代器。
- 非常量容器
- 常量容器
- begin
- cbegin
#include <string_view>
int main()
{
std::string_view str = "Hello";
auto it = str.cbegin(); // Type: std::string_view::const_iterator
*it = 'J'; // ❌ Error!
}
#include <string_view>
int main()
{
std::string_view str = "Hello";
auto it = str.cbegin(); // Type: std::string_view::const_iterator
*it = 'J'; // ❌ Error!
}
- begin
- cbegin
#include <string_view>
int main()
{
const std::string_view str = "Hello";
auto it = str.begin(); // Type: std::string_view::const_iterator
*it = 'J'; // ❌ Error!
}
#include <string_view>
int main()
{
const std::string_view str = "Hello";
auto it = str.cbegin(); // Type: std::string_view::const_iterator
*it = 'J'; // ❌ Error!
}
示例
Main.cpp
#include <iostream>
#include <string_view>
#include <type_traits>
int main()
{
std::string_view str_view("abcd");
auto begin = str_view.begin();
auto cbegin = str_view.cbegin();
std::cout << *begin << '\n';
std::cout << *cbegin << '\n';
std::cout << std::boolalpha << (begin == cbegin) << '\n';
std::cout << std::boolalpha << (*begin == *cbegin) << '\n';
static_assert(std::is_same<decltype(begin), decltype(cbegin)>{});
}
输出
a
a
true
true