Skip to main content

std::string begin()/cbegin() method

// Nonconst version
constexpr iterator begin() noexcept;

// Const version
constexpr const_iterator begin() const noexcept;
constexpr const_iterator cbegin() const noexcept;

Returns an iterator

to the first element of the string.

If the array is empty, the returned iterator will be equal to end().

Parameters

(none)

Return value

Iterator to the first element.

Complexity

Constant - O(1).

Notes

For a container c, the expression *c.begin() is equivalent to c.front().

Difference between begin and cbegin

For a const container c, begin and cbegin are the same - c.begin() == c.cbegin()

For non-const container of type c they return different iterators:

#include <string>

int main()
{
std::string str = "Hello";
auto it = str.begin(); // Type: std::string::iterator
*it = 'J'; // ✔ Ok
}

Example

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
}
Output
exemplar
e
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::string begin()/cbegin() method

// Nonconst version
constexpr iterator begin() noexcept;

// Const version
constexpr const_iterator begin() const noexcept;
constexpr const_iterator cbegin() const noexcept;

Returns an iterator

to the first element of the string.

If the array is empty, the returned iterator will be equal to end().

Parameters

(none)

Return value

Iterator to the first element.

Complexity

Constant - O(1).

Notes

For a container c, the expression *c.begin() is equivalent to c.front().

Difference between begin and cbegin

For a const container c, begin and cbegin are the same - c.begin() == c.cbegin()

For non-const container of type c they return different iterators:

#include <string>

int main()
{
std::string str = "Hello";
auto it = str.begin(); // Type: std::string::iterator
*it = 'J'; // ✔ Ok
}

Example

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
}
Output
exemplar
e
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.