C ++ 98
I think you need to consider that the Meyers statement refers to C ++ 98. It's hard to say today, but if I remember correctly
- it was just not easy to get a const_iterator for a non const container at all
- If you have a const_iterator, you could hardly use it, since most position arguments (for all?) For the container member functions should have been iterators, not const_iterators
eg.
std::vector<int> container;
would take
static_cast<std::vector<int>::const_iterator>(container.begin())
to get a const_iterator that would greatly inflate a simple .find, and even if you had your result, then
std::vector<int>::const_iterator i = std::find(static_cast<std::vector<int>::const_iterator>(container.begin()), static_cast<std::vector<int>::const_iterator>(container.end()),42);
it would not be possible to use your std :: vector :: const_iterator to insert into a vector or any other member function that would expect iterators for a position. And there was no way to get an iterator from a constant iterator. There is no casting method for this (exists?).
Since a constant iterator does not mean that the container cannot be changed, but only the element that it points to cannot be changed (the constant iterator is the equivalent of a pointer to const) , which was a really big bunch of crap that you have to deal with cases.
Today the opposite is true.
const iterators are easy to get with cbegin, etc. even for non const containers and all (?) member functions that take positions have constant iterators as their arguments, so there is no need for any conversion.
std::vector<int> container; auto i = std::find(container.cbegin(), container.cend(), 42); container.insert(i, 43);
So what once was
Prefer iterators over const_iterators
today really really should be
Prefer const_iterators over iterators
since the first is simply an artifact of historical implementation deficits.
DrSvanHay Aug 22 '17 at 19:25 2017-08-22 19:25
source share