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).
Related videos on Youtube
Author by
Simplicity
Updated on July 09, 2022Comments
-
Simplicity almost 2 years
How do I iterate over this C++ vector?
vector<string> features = {"X1", "X2", "X3", "X4"};
-
Niklas B. almost 12 yearsYeah, that one's pretty trivial to find.
-
-
Alok Save almost 12 yearsPerhaps you means
++i
and noti++
. -
Rontogiannis Aristofanis almost 12 yearsActually it's the same thing.
-
Alok Save almost 12 yearsNo, it is not! and you should be using a
const_iterator
not just aiterator
.This is boiler plate code, You should learn it well and well enough to get it right even if asked when asleep. -
mfontanini almost 12 yearsAlso, 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 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 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 about 9 yearsI 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 about 9 years@FanaticD I agree :)