What is the difference between a const_iterator
and an iterator
and where would you use one over the other?
7 Answers
const_iterator
s don't allow you to change the values that they point to, regular iterator
s do.
As with all things in C++, always prefer const
, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not const
to change the pointed-to value).
-
10In a perfect world that would be the case. But with C++ const is only as good as the person who wrote the code :(– JaredParNov 21, 2008 at 17:56
-
mutable exists for a very good reason. It is rarely used, and looking at Google Code Search, there appears to be fair percentage of valid uses. The keyword is a very powerful optimization tool, and it's not like removing it would improve const-correctness(coughpointerscoughandcoughreferencescough)– copproNov 21, 2008 at 19:23
-
3More like a powerful hack. Of all the instances I have ever seen of the use of the 'mutable' keyword, all but one was an accurate indicator that the code was poorly written and mutable was needed as a hack to get around the defects. Nov 21, 2008 at 21:54
-
7It does have legitimate uses, like caching the results of a long calculation within a const class. On the other hand, that's pretty much the only time I've used a mutable in nearly twenty years of C++ development. Nov 22, 2008 at 3:26
-
A generic example for using const_iterator would be when the iterator is an rvalue Oct 27, 2019 at 6:02
They should pretty much be self-explanatory. If iterator points to an element of type T, then const_iterator points to an element of type 'const T'.
It's basically equivalent to the pointer types:
T* // A non-const iterator to a non-const element. Corresponds to std::vector<T>::iterator
T* const // A const iterator to a non-const element. Corresponds to const std::vector<T>::iterator
const T* // A non-const iterator to a const element. Corresponds to std::vector<T>::const_iterator
A const iterator always points to the same element, so the iterator itself is const. But the element it points to does not have to be const, so the element it points to can be changed. A const_iterator is an iterator that points to a const element, so while the iterator itself can be updated (incremented or decremented, for example), the element it points to can not be changed.
-
2"A const iterator always points to the same element," This is incorrect. Nov 21, 2008 at 21:55
-
3How so? Note the missing underscore. I'm contrasting a variable of type const std::vector<T>::iterator with std::vector<T>::const_iterator. In the former case, the iterator itself is const, so it can't be modified, but the element it references can be modified freely.– jalfNov 21, 2008 at 22:18
-
4
-
5@JohnDibling Upvoted for explaining the subtlety between
const iterater
andconst_iterator
. Apr 3, 2015 at 13:49
Unfortunaty, a lot of the methods for the STL containers takes iterators instead of const_iterators as parameters. So if you have a const_iterator, you can't say "insert an element before the element that this iterator points to" (saying such a thing is not conceptually a const violation, in my opinion). If you want do that anyway, you have to convert it to a non-const iterator using std::advance() or boost::next(). Eg. boost::next(container.begin(), std::distance(container.begin(), the_const_iterator_we_want_to_unconst)). If container is a std::list, then the running time for that call will be O(n).
So the universal rule to add const wherever it is "logical" to do so, is less universal when it comes to STL containers.
However, boost containers take const_iterators (eg. boost::unordered_map::erase()). So when you use boost containers you can be "const agressive". By the way, do anyone know if or when the STL containers will be fixed?
-
1It may be a matter of opinion. In the case of
vector
anddeque
, inserting one element invalidates all existing iterators, which isn't veryconst
. But I do see your point. Such operations are protected by containerconst
-ness, not the iterators. And I do wonder why there isn't a const-to-nonconst iterator conversion function in the standard container interface. Dec 18, 2010 at 23:24 -
You are correct Potatoswatter, I am to categorical, it is a matter of opinion for the random access containers and container.begin() + (the_const_iterator_we_want_to_unconst – container.begin()) is O(1) anyway. I also wonder why there is no conversion function for the non-random access containers, but maybe there is a good reason? Do you know if there is some reason that the functions for the non-random access containers do not take const_iterators? Dec 19, 2010 at 23:37
-
"saying such a thing is not conceptually a const violation, in my opinion" - this is a very interesting comment, I have the following thoughts on the topic. With simple pointers, one can say
int const * foo;
int * const foo;
andint const * const foo;
all three are valid and useful, each in their own way.std::vector<int> const bar
should be the same as the second one, but it is unfortunately often treated like the third. The root cause of the problem is that we can't saystd::vector<int const> bar;
when means there's no way to get the same effect asint const *foo;
in a vector.– dgnuffOct 28, 2018 at 4:43
Minimal runnable examples
Non-const iterators allow you to modify what they point to:
std::vector<int> v{0};
std::vector<int>::iterator it = v.begin();
*it = 1;
assert(v[0] == 1);
Const iterators don't:
const std::vector<int> v{0};
std::vector<int>::const_iterator cit = v.begin();
// Compile time error: cannot modify container with const_iterator.
//*cit = 1;
As shown above, v.begin()
is const
overloaded, and returns either iterator
or const_iterator
depending on the const-ness of the container variable:
- How does begin() know which return type to return (const or non-const)?
- how does overloading of const and non-const functions work?
A common case where const_iterator
pops up is when this
is used inside a const
method:
class C {
public:
std::vector<int> v;
void f() const {
std::vector<int>::const_iterator it = this->v.begin();
}
void g(std::vector<int>::const_iterator& it) {}
};
const
makes this
const, which makes this->v
const.
You can usually forget about it with auto
, but if you starting passing those iterators around, you will need to think about them for the method signatures.
Much like const and non-const, you can convert easily from non-const to const, but not the other way around:
std::vector<int> v{0};
std::vector<int>::iterator it = v.begin();
// non-const to const.
std::vector<int>::const_iterator cit = it;
// Compile time error: cannot modify container with const_iterator.
//*cit = 1;
// Compile time error: no conversion from const to no-const.
//it = ci1;
Which one to use: analogous to const int
vs int
: prefer const iterators whenever you can use them (when you don't need to modify the container with them), to better document your intention of reading without modifying.
(as others have said) const_iterator doesn't allow you modify the elements to which it points, this is useful inside of const class methods. It also allows you to express your intent.
ok Let me explain it with very simple example first without using constant iterator consider we have collection of random integers collection "randomData"
for(vector<int>::iterator i = randomData.begin() ; i != randomData.end() ; ++i)*i = 0;
for(vector<int>::const_iterator i = randomData.begin() ; i!= randomData.end() ; ++i)cout << *i;
As can be seen for writing/editing data inside collection normal iterator is used but for reading purpose constant iterator has been used . If you try using constant iterator in first for loop you will get error . As a thumb rule use constant iterator to read data inside collection .