std::map end() method
- od C++11
- do C++11
// Non const version
iterator end() noexcept;
// Const version
iterator end() const noexcept;
// Const version
const_iterator cend() const noexcept;
// Non const version
iterator end();
// Const version
const_iterator cend();
Returns an iterator
to the element past-the-end of the array. If the array is empty, the returned iterator will be equal tobegin()
.
Attempting to dereference a past-the-end iterator is undefined behaviour
.Parameters
(none)
Return value
Iterator to the first element.
Exceptions
(none)
Complexity
Constant - O(1).
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 <map>
int main()
{
std::map<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = arr.end(); // Type: std::map<int, float>::iterator
*std::prev(it) = 5; // ✔ Ok
}
#include <map>
int main()
{
std::map<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = arr.cend(); // Type: std::map<int, float>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
- end
- cend
#include <map>
int main()
{
const std::map<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = arr.end(); // Type: std::map<int, float>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
#include <map>
int main()
{
const std::map<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = arr.cend(); // Type: std::map<int, float>::const_iterator
*std::prev(it) = 5; // ❌ Error!
}
Example
Main.cpp
#include <iomanip>
#include <iostream>
#include <map>
#include <string_view>
int main()
{
const std::map<int, std::string_view> coins {
{10, "dime"},
{100, "dollar"},
{50, "half dollar"},
{5, "nickel"},
{1, "penny"},
{25, "quarter"}
}; // initializer entries in name alphabetical order
std::cout << "US coins in circulation, largest to smallest denomination:\n";
for (auto it = coins.crbegin(); it != coins.crend(); ++it) {
std::cout << std::setw(11) << it->second << " = ¢" << it->first << '\n';
}
}
Output
US coins in circulation, largest to smallest denomination:
dollar = ¢100
half dollar = ¢50
quarter = ¢25
dime = ¢10
nickel = ¢5
penny = ¢1
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.