std::string begin()/cbegin() method
- od C++20
- od C++11
- do 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;
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:
- Non const container
- Const container
- 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!
}
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.
Hover to see the original license.