How to iterate over a c ++ string vector?

How to iterate over this C ++ vector?

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

+8
c ++ loops vector
source share
2 answers

Try the following:

 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 use C ++ 11, this is also legal:

 for(auto i : features) { // process i cout << i << " "; // this will print all the contents of *features* } 
+22
source share

The C ++ 11 that you use if it compiles allows the following:

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

This is a for range based loop.

If you do not want to mutate the function, you can also declare it as a string const& (or just string , but this will cause an unnecessary copy).

+8
source share

All Articles