9

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?

user904963
  • 1,520
  • 2
  • 15
  • 33
  • 9
    Note: C++ will have `std::cbegin` come C++14. – eq- Nov 08 '13 at 18:32
  • 1
    "Why does C++ not have ___" 1) Nobody wanted it enough to do it. 2) It doesn't fit well within C++'s principles (don't pay for what you don't use, don't assume much about the platform, etc.) 3) Time constraints. 4) Oversight. In your case, likely 4. – GManNickG Nov 08 '13 at 23:43
  • Last year Nicolas Bolas said it was an oversight: http://stackoverflow.com/questions/12001410/what-is-the-reason-behind-cbegin-cend#comment16015196_12001519 Not sure if that's true but it's quite likely. – jogojapan Nov 10 '13 at 00:31
  • 1
    @GManNickG - I think it's useful to know which one of the four it is. "Doesn't fit with the principles" means it will never be there. "Oversight" or "time constraint" mean there's a good chance it will get in to the standard sooner or later. – Jeremiah Nov 19 '13 at 19:35

2 Answers2

40

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

Herb Sutter
  • 1,888
  • 1
  • 14
  • 14
3

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.

Michael Simbirsky
  • 3,045
  • 1
  • 12
  • 24
  • 6
    Right... but that isn't really the issue here. E.g. if I used a container with `std::find`, I would use `std::cbegin` and `std::cend` to be consistent even for a non`const` container. – user904963 Nov 09 '13 at 00:58