25

How do I iterate over this C++ vector?

vector<string> features = {"X1", "X2", "X3", "X4"};

Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
Simplicity
  • 47,404
  • 98
  • 256
  • 385

2 Answers2

38

Try this:

for(vector<string>::const_iterator i = features.begin(); i != features.end(); ++i) {
    // process i
    cout << *i << " "; // this will print all the contents of *features*
}

If you are using C++11, then this is legal too:

for(auto i : features) {
    // process i
    cout << i << " "; // this will print all the contents of *features*
} 
Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
  • Perhaps you means `++i` and not `i++`. – Alok Save Jun 23 '12 at 14:42
  • 1
    Actually it's the same thing. – Rontogiannis Aristofanis Jun 23 '12 at 14:44
  • 11
    [No, it is not!](http://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c) and you should be using a `const_iterator` not just a `iterator`.This is boiler plate code, You should learn it well and well enough to get it right even if asked when asleep. – Alok Save Jun 23 '12 at 14:46
  • Also, the `i` variable in the range-based for loop should be a const reference. Otherwise you are creating unnecessary copies of the vector's strings. – mfontanini Jun 23 '12 at 14:53
  • 4
    @Als - That's old info. Current compilers have no problems inlining either operator++ for std::vector, and optimize away any unused copies. – Bo Persson Jun 23 '12 at 14:53
  • 1
    @BoPersson: You never know which compiler one might get to put up with,Besides it never hurts to write more correct and better code, especially in case of boiler plate codes. – Alok Save Jun 23 '12 at 14:55
  • 3
    I believe that in this context, it doesn't really matter if it is ++i or i++ and therefore there is no "correct" or "incorrect" way or even "better" way of coding. Given this context, there is no difference between post and pre incrementation. – FanaticD Apr 05 '15 at 08:01
  • @FanaticD I agree :) – Rontogiannis Aristofanis Apr 05 '15 at 16:43
14

C++11, which you are using if this compiles, allows the following:

for (string& feature : features) {
    // do something with `feature`
}

This is the range-based for loop.

If you don’t want to mutate the feature, you can also declare it as string const& (or just string, but that will cause an unnecessary copy).

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214