Skip to main content

std::set 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 set. If the set 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 <set>

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

Example​

Main.cpp
#include <algorithm>
#include <iostream>
#include <set>

int main() {
std::set<int> set = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
std::for_each(set.cbegin(), set.cend(), [](int x) {
std::cout << x << ' ';
});
std::cout << '\n';
}
Output
1 2 3 4 5 6 9
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::set 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 set. If the set 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 <set>

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

Example​

Main.cpp
#include <algorithm>
#include <iostream>
#include <set>

int main() {
std::set<int> set = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
std::for_each(set.cbegin(), set.cend(), [](int x) {
std::cout << x << ' ';
});
std::cout << '\n';
}
Output
1 2 3 4 5 6 9
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.