Although when we traversing through begin(),end() and cbegin(),cend(). They gives us same result.But what is the difference between them?
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<char,int>mp;
mp['a']=200;
mp['b'] = 100;
mp['c']=300;
for(auto it =mp.cbegin();it!=mp.cend();it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
cout<<endl;
for(auto it =mp.begin();it!=mp.end();it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
begin() returns an iterator to beginning while cbegin() returns a const_iterator to beginning. The basic difference between these two is iterator (i.e begin() ) lets you change the value of the object it is pointing to and const_iterator will not let you change the value of the object.
The set::cbegin() is a built-in function in C++ STL which returns a constant iterator pointing to the first element in the container. The iterator cannot be used to modify the elements in the set container.
What is the difference between begin () and rend () ? begin returns an iterator to the first element of the container. rend returns a reverse iterator to one before the first element of the container (which is one past the last element in the reverse iterator range).
std::vector::cbegin Returns a const_iterator pointing to the first element in the container. A const_iterator is an iterator that points to const content.
cbegin: Returns a const_iterator pointing to the first element in the container.
begin: Returns an iterator pointing to the first element in the sequence.
cend: Returns a const_iterator pointing to the past-the-end element in the container.
end: Returns an iterator pointing to the past-the-end element in the sequence.
http://www.cplusplus.com/reference/map/map/cbegin/ http://www.cplusplus.com/reference/iterator/begin/?kw=begin http://www.cplusplus.com/reference/map/map/cend/ http://www.cplusplus.com/reference/iterator/end/?kw=end
There are two differences, which are very much related.
The first difference is that cbegin
has no overloads, and it is const qualified, while begin
is overloaded by two functions one of which is const qualified and the other is not.
The second difference is in the type of the iterator that they return. As per documentation, cbegin
returns a const_iterator
, while one overload of begin
return iterator
and the other returns const_iterator
(like cbegin
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With