2

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

Ross
  • 14,266
  • 12
  • 60
  • 91

4 Answers4

7

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

Ross
  • 14,266
  • 12
  • 60
  • 91
Christian Stieber
  • 9,954
  • 24
  • 23
  • Ah, thanks. Can you explain why it will still be copied, and by "I like to return references" do you mean return a pointer to the original vector? Thanks. – Ross Jul 08 '12 at 19:32
  • 1
    @Ross, http://stackoverflow.com/questions/57483/what-are-the-differences-between-pointer-variable-and-reference-variable-in-c – chris Jul 08 '12 at 19:36
  • 1
    @Ross whatever you do, don't return references to local variables. – R. Martinho Fernandes Jul 08 '12 at 20:05
  • I won't. The function returning the vector is an external library, so I was trying to optimise how I deal with a quick iteration. Any suggestions welcome, or if I am making a fuss out of nothing that would be good to know... – Ross Jul 08 '12 at 20:32
7

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 2
    Or just `for (int i : getIntVector())` if you don't care about `it` at all and just want a quick iteration. – MSalters Jul 08 '12 at 21:28
5

Use vector<int>::const_iterator instead.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
4

You can use vector<int>::const_iterator.

fdomig
  • 4,417
  • 3
  • 26
  • 39