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

2019-03-24 13:20发布

问题:

How do I iterate over this C++ vector?

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

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


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



标签: c++ vector loops