How do I iterate over this C++ vector?
vector<string> features = {"X1", "X2", "X3", "X4"};
How do I iterate over this C++ vector?
vector<string> features = {"X1", "X2", "X3", "X4"};
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*
}
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).