如何迭代 C++ 字符串向量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11170349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I Iterate over a vector of C++ strings?
提问by Simplicity
How do I iterate over this C++ vector?
我如何迭代这个 C++ 向量?
vector<string> features = {"X1", "X2", "X3", "X4"};
vector<string> features = {"X1", "X2", "X3", "X4"};
回答by Rontogiannis Aristofanis
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:
如果您使用的是 C++11,那么这也是合法的:
for(auto i : features) {
// process i
cout << i << " "; // this will print all the contents of *features*
}
回答by Konrad Rudolph
C++11, which you are using if this compiles, allows the following:
如果编译通过,您正在使用的 C++11 允许以下内容:
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).
如果您不想改变该功能,您也可以将其声明为string const&
(或只是string
,但这会导致不必要的副本)。