如何迭代C ++字符串向量?

时间:2012-06-23 14:38:58

标签: c++ vector loops

如何迭代这个C ++向量?

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

2 个答案:

答案 0 :(得分:29)

试试这个:

for(vector<string>::const_iterator i = features.begin(); i != features.end(); ++i) {
    // process i
    cout << *i << " "; // this will print all the contents of *features*
}

如果您使用的是C ++ 11,那么这也是合法的:

for(auto i : features) {
    // process i
    cout << i << " "; // this will print all the contents of *features*
} 

答案 1 :(得分:9)

C ++ 11,如果编译,您正在使用它,允许以下内容:

for (string& feature : features) {
    // do something with `feature`
}

This is the range-based for loop.

如果您不想改变该功能,您也可以将其声明为string const&(或仅string,但这会导致不必要的副本。)