std::string end() method
- since C++20
- since C++11
- until C++11
// Non-const version
constexpr iterator end() noexcept;
// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;
// Non-const version
iterator end() noexcept;
// Const version
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
// Non-const version
iterator end();
// Const version
const_iterator end() const;
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:
- Non const container
- Const container
- end
- cend
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.end(); // Type: std::string::iterator
*std::prev(it) = 'J'; // ✔ Ok
}
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.cend(); // Type: std::string::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
- end
- cend
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.end(); // Type: std::string::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.cend(); // Type: std::string::const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
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.
Hover to see the original license.