【发布时间】:2012-06-23 14:38:57
【问题描述】:
如何迭代这个 C++ 向量?
vector<string> features = {"X1", "X2", "X3", "X4"};
【问题讨论】:
-
是的,这个很容易找到。
如何迭代这个 C++ 向量?
vector<string> features = {"X1", "X2", "X3", "X4"};
【问题讨论】:
试试这个:
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*
}
【讨论】:
const_iterator 而不仅仅是iterator。这是样板代码,即使在睡着时被问到,您也应该好好学习它以使其正确.
如果编译,您正在使用的 C++11 允许以下内容:
for (string& feature : features) {
// do something with `feature`
}
This is the range-based for loop.
如果您不想更改该功能,您也可以将其声明为string const&(或只是string,但这会导致不必要的复制)。
【讨论】: