如何迭代C++;串? 我如何迭代这个C++向量?< /p>
如何迭代C++;串? 我如何迭代这个C++向量?< /p>,c++,vector,loops,C++,Vector,Loops,矢量特征={“X1”、“X2”、“X3”、“X4”}C++11(如果进行编译,则使用它)允许以下操作: for (string& feature : features) { // do something with `feature` } 如果您不想改变该功能,还可以将其声明为string const&(或仅声明string,但这将导致不必要的副本)。尝试以下操作: for(vector<string>::const_iterator i = features.b
矢量特征={“X1”、“X2”、“X3”、“X4”}代码>C++11(如果进行编译,则使用它)允许以下操作:
for (string& feature : features) {
// do something with `feature`
}
如果您不想改变该功能,还可以将其声明为string const&
(或仅声明string
,但这将导致不必要的副本)。尝试以下操作:
for(vector<string>::const_iterator i = features.begin(); i != features.end(); ++i) {
// process i
cout << *i << " "; // this will print all the contents of *features*
}
for(vector::const_迭代器i=features.begin();i!=features.end();++i){
//过程一
是的,这是很容易找到的。事实上也是一样。你应该使用const_迭代器,而不仅仅是迭代器。这是锅炉板代码,你应该学得很好,即使在睡觉时被问到也能正确使用。@Als-这是老信息。当前的编译器在内联任何一个操作都没有问题erator++用于std::vector,并优化掉所有未使用的副本。@Boperson:你永远不知道你可以忍受哪种编译器,而且编写更正确、更好的代码也不会有什么坏处,尤其是在锅炉板代码的情况下。我相信在这种情况下,它是++I还是I++并不重要,因此没有“正确的”或者是“不正确”的编码方式,甚至是“更好”的编码方式。在这种情况下,增量后和增量前没有区别。
for(auto i : features) {
// process i
cout << i << " "; // this will print all the contents of *features*
}