std::vector end() method
- since C++20
- since C++11
- until C++11
// prism-push-types:iterator,const_iterator
// Non-const version
constexpr iterator end() noexcept;
// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;
// prism-push-types:iterator,const_iterator
// 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 behavior
.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 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 <vector>
int main()
{
std::vector<int> arr = {1, 2, 3, 4, 5};
auto it = arr.end(); // Type: std::vector<int>::iterator
*std::prev(it) = 5; // ✔ Ok
}
#include <vector>
int main()
{
std::vector<int> arr = {1, 2, 3, 4, 5};
auto it = arr.cend(); // Type: std::vector<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
- end
- cend
#include <vector>
int main()
{
const std::vector<int> arr = {1, 2, 3, 4, 5};
auto it = arr.end(); // Type: std::vector<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
#include <vector>
int main()
{
const std::vector<int> arr = {1, 2, 3, 4, 5};
auto it = arr.cend(); // Type: std::vector<int>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
Example
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
int main()
{
std::vector<int> nums {1, 2, 4, 8, 16};
std::vector<std::string> fruits {"orange", "apple", "raspberry"};
std::vector<char> empty;
// Print vector.
std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sums all integers in the vector nums (if any), printing only the result.
std::cout << "Sum of nums: "
<< std::accumulate(nums.begin(), nums.end(), 0) << '\n';
// Prints the first fruit in the vector fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.begin() << '\n';
if (empty.begin() == empty.end())
std::cout << "vector 'empty' is indeed empty.\n";
}
1 2 4 8 16
Sum of nums: 31
First fruit: orange
vector 'empty' is indeed empty.
Hover to see the original license.