Skip to main content

std::string end() method

// Non-const version
constexpr iterator end() noexcept;

// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;

Returns an iterator

to the element past-the-end of the array.
If the array is empty, the returned iterator will be equal to begin().

Attempting to dereference a past-the-end iterator is undefined behaviour

.

Parameters

(none)

Return value

Iterator to the character following the last character

Complexity

Constant - O(1)..

Notes

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

Difference between end and cend

For a const container c, end and cend are the same - c.end() == c.cend()

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

#include <string>

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

Example

Main.cpp
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>

int main()
{
std::string s("Exemparl");
std::next_permutation(s.begin(), s.end());

std::string c;
std::copy(s.cbegin(), s.cend(), std::back_inserter(c));
std::cout << c <<'\n'; // "Exemplar"
}
Output
Exemplar
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 end() method

// Non-const version
constexpr iterator end() noexcept;

// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;

Returns an iterator

to the element past-the-end of the array.
If the array is empty, the returned iterator will be equal to begin().

Attempting to dereference a past-the-end iterator is undefined behaviour

.

Parameters

(none)

Return value

Iterator to the character following the last character

Complexity

Constant - O(1)..

Notes

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

Difference between end and cend

For a const container c, end and cend are the same - c.end() == c.cend()

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

#include <string>

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

Example

Main.cpp
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>

int main()
{
std::string s("Exemparl");
std::next_permutation(s.begin(), s.end());

std::string c;
std::copy(s.cbegin(), s.cend(), std::back_inserter(c));
std::cout << c <<'\n'; // "Exemplar"
}
Output
Exemplar
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.