unordered_map cend in C++ STL
The unordered_map::cend() is a built-in function in C++ STL which returns an iterator pointing to the position past the end element in the container or in one of its bucket. In an unordered_map object, there is no guarantee that which specific element is considered its first element. But all the elements in the container are covered since the range goes from its begin to its end until invalidated.
There are two variant of this function.
Syntax-1:
unordered_map.cend()
Parameters: This function does not accept any parameter.
Return type: The function returns an iterator to the element past the end of the container.
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_map< int , int > ump;
ump[1] = 2;
ump[3] = 4;
ump[5] = 6;
for ( auto it = ump.cbegin(); it != ump.cend(); ++it)
cout << it->first << " " << it->second << endl;
return 0;
}
|
Syntax-2:
unordered_map.cend ( size n )
Parameters: This function accepts parameter size n which should be lower than bucket count.
Return type: The function returns an iterator to the one of its bucket count.
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_map< int , int > ump;
ump[1] = 2;
ump[3] = 4;
ump[5] = 6;
cout << "unordered_map bucket contains \n" ;
for ( int i = 0; i < ump.bucket_count(); i++) {
cout << "Bucket " << i << " contains " ;
for ( auto it = ump.cbegin(i); it != ump.cend(i); ++it)
cout << it->first << " " << it->second;
cout << endl;
}
return 0;
}
|
Output:
unordered_map bucket contains
Bucket 0 contains
Bucket 1 contains 1 2
Bucket 2 contains
Bucket 3 contains 3 4
Bucket 4 contains
Bucket 5 contains 5 6
Bucket 6 contains
How is cend() different from end()?
cend() is const version of end(). Similarly cbegin() is a const version of begin(). For example, the following code shows compiler error because we try to modify value in iterator.
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_map< int , int > ump;
ump[1] = 2;
ump[3] = 4;
ump[5] = 6;
for ( auto it = ump.cbegin(); it != ump.cend(); ++it)
it->second = 10;
return 0;
}
|
Output :
Compilation Error in CPP code :- prog.cpp: In function 'int main()':
prog.cpp:19:20: error: assignment of member 'std::pair::second' in read-only object
it->second = 10; // COMPILER ERROR
Last Updated :
18 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...