How do I iterate over this C++ vector?
vector<string> features = {"X1", "X2", "X3", "X4"};
Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() .
To remove all copies of an element from a vector , you can use std::remove like this: v. erase(std::remove(v. begin(), v.
Conclusion: Out of all the methods, Vector seems to be the best way for creating an array of Strings in C++.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With