std::unordered_multiset begin()/cbegin() method
- od C++11
// Non const version
iterator begin() noexcept;
// Const version
const_iterator begin() const noexcept;
// Const version
const_iterator cbegin() const noexcept;
Returns an iterator
to the first element of the vector. If the array is empty, the returned iterator will be equal toend()
.
Parameters
(none)
Return value
Iterator to the first element.
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:
- Non const container
- Const container
- begin
- cbegin
#include <unordered_set>
#include <string>
int main()
{
std::unordered_multiset<std::string> multiset = { "abc", "Hello World!", "abc", "asd" };
auto it = multiset.begin(); // Type: std::unordered_multiset<std::string>::iterator
it->second = 5; // ✔ Ok
}
#include <unordered_set>
#include <string>
int main()
{
std::unordered_multiset<std::string> multiset = { "abc", "Hello World!", "abc", "asd" };
{ "key1", 1 },
{ "key2", 2 },
{ "key3", 3 },
};
auto it = multiset.cbegin(); // Type: std::unordered_multiset<std::string>::const_iterator
it->second = 5; // ❌ Error!
}
- begin
- cbegin
#include <unordered_set>
#include <string>
int main()
{
std::unordered_multiset<std::string> multiset = { "abc", "Hello World!", "abc", "asd" };
auto it = multiset.begin(); // Type: std::unordered_multiset<std::string>::const_iterator
it->second = 5; // ❌ Error!
}
#include <unordered_set>
#include <string>
int main()
{
std::unordered_multiset<std::string> multiset = { "abc", "Hello World!", "abc", "asd" };
auto it = multiset.cbegin(); // Type: std::unordered_multiset<std::string>::const_iterator
it->second = 5; // ❌ Error!
}
Example
Main.cpp
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_set>
int main() {
const std::unordered_multiset<std::string> words = {
"some", "words", "to", "count",
"count", "these", "words"
};
for (auto it = words.begin(); it != words.end(); ) {
auto cnt = words.count(*it);
std::cout << *it << ":\t" << cnt << '\n';
std::advance(it, cnt); // all cnt elements have equivalent keys
}
}
Possible Output
some: 1
words: 2
to: 1
count: 2
these: 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.