跳到主要内容

std::string_view begin()/cbegin() 方法

// 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::stringstd::vector)不同,begincbegin 都返回相同的迭代器。

#include <string_view>

int main()
{
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
本文源自 此 CppReference 页面。它可能经过修改以进行改进或满足编辑偏好。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string_view begin()/cbegin() 方法

// 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::stringstd::vector)不同,begincbegin 都返回相同的迭代器。

#include <string_view>

int main()
{
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
本文源自 此 CppReference 页面。它可能经过修改以进行改进或满足编辑偏好。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。