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

xtfmy6hx  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(138)

我如何迭代这个C++向量?
vector<string> features = {"X1", "X2", "X3", "X4"};

jum4pzuy

jum4pzuy1#

试试这个:

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*
}
mqkwyuun

mqkwyuun2#

C++11(如果编译此代码,您将使用它)允许以下操作:

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

This is the range-based for loop.
如果不想改变特性,也可以将其声明为string const&(或者只声明为string,但这会导致不必要的复制)。

相关问题