Przejdź do głównej zawartości

std::map begin() method

// Non const version
iterator begin() noexcept;

// Const version
iterator begin() const noexcept;

// Const version
const_iterator cbegin() const noexcept;

Returns an iterator

to the first element of the map. If the array is empty, the returned iterator will be equal to end().

Parameters

(none)

Return value

Iterator to the first element.

Exceptions

(none)

Complexity

Constant - O(1).

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:

#include <map>

int main()
{
std::map<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = map.begin(); // Type: std::map<int, float>::iterator
*it = 5; // ✔ Ok
}

Example

Main.cpp
#include <iostream>
#include <map>

int main() {
std::map<int, float> num_map;
num_map[4] = 4.13;
num_map[9] = 9.24;
num_map[1] = 1.09;
// calls a_map.begin() and a_map.end()
for (auto it = num_map.begin(); it != num_map.end(); ++it) {
std::cout << it->first << ", " << it->second << '\n';
}
}
Output
1, 1.09
4, 4.13
9, 9.24
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::map begin() method

// Non const version
iterator begin() noexcept;

// Const version
iterator begin() const noexcept;

// Const version
const_iterator cbegin() const noexcept;

Returns an iterator

to the first element of the map. If the array is empty, the returned iterator will be equal to end().

Parameters

(none)

Return value

Iterator to the first element.

Exceptions

(none)

Complexity

Constant - O(1).

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:

#include <map>

int main()
{
std::map<int, float> map = { {1, 1.f}, {2, 3.f}, {5, 8.f} };
auto it = map.begin(); // Type: std::map<int, float>::iterator
*it = 5; // ✔ Ok
}

Example

Main.cpp
#include <iostream>
#include <map>

int main() {
std::map<int, float> num_map;
num_map[4] = 4.13;
num_map[9] = 9.24;
num_map[1] = 1.09;
// calls a_map.begin() and a_map.end()
for (auto it = num_map.begin(); it != num_map.end(); ++it) {
std::cout << it->first << ", " << it->second << '\n';
}
}
Output
1, 1.09
4, 4.13
9, 9.24
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.