How do I Iterate over a vector of C++ strings?

65,956

Solution 1

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*
} 

Solution 2

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

Share:
65,956

Related videos on Youtube

Simplicity
Author by

Simplicity

Updated on July 09, 2022

Comments

  • Simplicity
    Simplicity almost 2 years

    How do I iterate over this C++ vector?

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

    • Niklas B.
      Niklas B. almost 12 years
      Yeah, that one's pretty trivial to find.
  • Alok Save
    Alok Save almost 12 years
    Perhaps you means ++i and not i++.
  • Rontogiannis Aristofanis
    Rontogiannis Aristofanis almost 12 years
    Actually it's the same thing.
  • Alok Save
    Alok Save almost 12 years
    No, it is not! 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.
  • mfontanini
    mfontanini almost 12 years
    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.
  • Bo Persson
    Bo Persson almost 12 years
    @Als - That's old info. Current compilers have no problems inlining either operator++ for std::vector, and optimize away any unused copies.
  • Alok Save
    Alok Save almost 12 years
    @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.
  • FanaticD
    FanaticD about 9 years
    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.
  • Rontogiannis Aristofanis
    Rontogiannis Aristofanis about 9 years
    @FanaticD I agree :)