Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate over a `const vector<int>`?

Tags:

c++

std

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....

like image 586
Ross Avatar asked Nov 19 '25 01:11

Ross


2 Answers

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...

like image 88
Christian Stieber Avatar answered Nov 20 '25 14:11

Christian Stieber


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.

like image 21
Nawaz Avatar answered Nov 20 '25 16:11

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!