Is it possible to iterate over a const vector<int>? Or, would this be undesirable anyway?
Given I have the function getIntVector which returns a vector<int> I can iterate over it with the following:
vector<int> vec = getIntVector();
vector<int>::iterator it;
for (it=vec.begin();it!=vec.end();++it) {}
But I can not do the following:
const vector<int> vec = getIntVector();
vector<int>::iterator it;
// complier throws error below
for (it=vec.begin();it!=vec.end();++it) {}
My thinking was that the vector would not be recreated by declaring it as a const....
1) you need a vector<int>::const_iterator to iterate through a "const" container
2) Your vector will still get copied; this may or may not be desireable. I like to return references...
If you're using C++11, you can use auto, and let the compiler infer the type from the initialization as:
for (auto it=vec.begin(); it!=vec.end(); ++it)
//^^^^ compiler will infer the type using the initialization expression
In C++03, however, you have to use const_iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With