Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the differences between begin(),end() and cbegin() ,cend()? [duplicate]

Tags:

c++

stl

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;
}
like image 251
Tanim_113 Avatar asked Apr 28 '18 00:04

Tanim_113


People also ask

What is the difference between begin () and Cbegin () in C++?

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.

What is Cbegin and Cend?

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.

Is Rend same as begin?

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).

What does Cbegin return?

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.


2 Answers

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

like image 55
Davide Avatar answered Oct 18 '22 03:10

Davide


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).

like image 26
eerorika Avatar answered Oct 18 '22 05:10

eerorika