Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between cbegin and begin for vector?

The member begin has two overloadings one of them is const_iterator begin() const;. There's also the cbegin const_iterator cbegin() const noexcept;. Both of them returns const_iterator to the begin of a list. What's the difference?

like image 790
user3663882 Avatar asked Jul 03 '15 14:07

user3663882


People also ask

What is begin in vector?

vector::begin() begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional iterator to the first element of the container.

What is the difference between a begin iterator and an end iterator?

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.

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.

What data type is Vector begin ()?

vector::begin() function is a bidirectional iterator used to return an iterator pointing to the first element of the container.


1 Answers

begin will return an iterator or a const_iterator depending on the const-qualification of the object it is called on.

cbegin will return a const_iterator unconditionally.

std::vector<int> vec; const std::vector<int> const_vec;  vec.begin(); //iterator vec.cbegin(); //const_iterator  const_vec.begin(); //const_iterator const_vec.cbegin(); //const_iterator 
like image 92
TartanLlama Avatar answered Sep 21 '22 11:09

TartanLlama