Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use standalone `std::begin` and for a const_iterator?

I like consistency. I recently asked the question of using std::begin vs. e.g. std::vector<int>::begin, and the unanimous decision seemed to be to use the former since it is more general. But I think I found a stick in the mud. Sometimes, you want to convey you will not change a container as you loop through it, hence calling std::vector<int>::cbegin. It would make your code quite asymmetric if you sometimes did iter = v.cbegin() and other times did iter = begin(v). Is there a way around this lack of symmetry, and would you still recommend std::begin given this knowledge? Why does C++ not have std::cbegin?

like image 877
user904963 Avatar asked Nov 08 '13 18:11

user904963


2 Answers

C++14 has cbegin/cend/etc. and it is starting to be available in major compilers.

like image 168
Herb Sutter Avatar answered Sep 20 '22 19:09

Herb Sutter


When your container is declared "const", for example, it is passed to a function as foo(const std::vector<int> & v), then std::begin will actually return a const_iterator.

like image 29
Michael Simbirsky Avatar answered Sep 23 '22 19:09

Michael Simbirsky