Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

How do I iterate over this C++ vector?

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

like image 963
Simplicity Avatar asked Jun 23 '12 14:06

Simplicity


People also ask

How do you iterate through a vector?

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() .

How do I remove a string from a vector string?

To remove all copies of an element from a vector , you can use std::remove like this: v. erase(std::remove(v. begin(), v.

Can a vector hold strings?

Conclusion: Out of all the methods, Vector seems to be the best way for creating an array of Strings in C++.


2 Answers

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* }  
like image 90
Rontogiannis Aristofanis Avatar answered Nov 17 '22 20:11

Rontogiannis Aristofanis


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

like image 42
Konrad Rudolph Avatar answered Nov 17 '22 20:11

Konrad Rudolph