In C++, std::string::cbegin() returns a const_iterator to the first character.
Use it when you want a read-only walk even on a non-const string. Include <string>. (C++11)
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Call cbegin for a read-only starting iterator.
C++
auto it = s.cbegin();
Call
What it does
s.cbegin()
const_iterator to the first character.
On a const string, begin() already returns a const_iterator. cbegin() makes the intent obvious on mutable strings.
Library declarations
C++
const_iterator cbegin() const noexcept;
Parameters
Parameter
Description
None
cbegin() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
const_iterator
Read-only iterator to the first character.
C++ Examples
Example 1 — Basic cbegin()
Read the first character.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "Read";
std::cout << *s.cbegin() << '\n';
return 0;
}
Output
R
How It Works
cbegin() points at the first character.
Dereferencing reads 'R'.
The iterator is const, so it cannot assign.
Example 2 — Loop With cbegin/cend
Print all characters read-only.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "xy";
for (auto it = s.cbegin(); it != s.cend(); ++it) {
std::cout << *it;
}
std::cout << '\n';
return 0;
}
Output
xy
How It Works
The loop uses const iterators.
Each character is printed.
No modification is possible through it.
Example 3 — Algorithm With Const Iters
Use find with cbegin/cend.
C++
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string s = "banana";
auto it = std::find(s.cbegin(), s.cend(), 'n');
if (it != s.cend()) {
std::cout << "index: " << (it - s.cbegin()) << '\n';
}
return 0;
}
Output
index: 2
How It Works
std::find searches the half-open range.
The first 'n' is at offset 2.
Using cbegin/cend keeps the search read-only.
Frequently Asked Questions
Returns a const_iterator to the first character.
To force a read-only iterator even when the string is non-const.