std::string begin()/cbegin() 方法
- 自 C++20 起
- 自 C++11 起
- 直到 C++11
// Nonconst version
constexpr iterator begin() noexcept;
// Const version
constexpr const_iterator begin() const noexcept;
constexpr const_iterator cbegin() const noexcept;
// Non const version
iterator begin() noexcept;
// Const version
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
// Non const version
iterator begin();
// Const version
const_iterator begin() const;
返回指向数组末尾之后元素的迭代器。
指向字符串的第一个元素。如果数组为空,返回的迭代器将等于 end()
。
参数
(无)
返回值
指向第一个元素的迭代器。
复杂度
常数 - O(1)。
备注
对于容器c
,表达式*c.begin()
等效于c.front()
。
begin 和 cbegin 的区别
对于 const 容器 c
,begin 和 cbegin 是相同的 - c.begin() == c.cbegin()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- begin
- cbegin
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.begin(); // Type: std::string::iterator
*it = 'J'; // ✔ Ok
}
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.cbegin(); // Type: std::string::const_iterator
*it = 'J'; // ❌ Error!
}
- begin
- cbegin
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.begin(); // Type: std::string::const_iterator
*it = 'J'; // ❌ Error!
}
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.cbegin(); // Type: std::string::const_iterator
*it = 'J'; // ❌ Error!
}
示例
Main.cpp
#include <string>
#include <iostream>
int main()
{
std::string s("Exemplar");
*s.begin() = 'e';
std::cout << s <<'\n';
auto i = s.cbegin();
std::cout << *i << '\n';
// *i = 'E'; // error: i is a constant iterator
}
输出
exemplar
e