【问题标题】:How do I Iterate over a vector of C++ strings? [closed]如何迭代 C++ 字符串向量? [关闭]
【发布时间】:2012-06-23 14:38:57
【问题描述】:

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

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

【问题讨论】:

  • 是的,这个很容易找到。

标签: c++ vector loops


【解决方案1】:

试试这个:

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

【讨论】:

  • 其实是一样的。
  • No, it is not! 并且您应该使用const_iterator 而不仅仅是iterator。这是样板代码,即使在睡着时被问到,您也应该好好学习它以使其正确.
  • @Als - 这是旧信息。当前的编译器为 std::vector 内联任一 operator++ 都没有问题,并优化掉任何未使用的副本。
  • @BoPersson:你永远不知道可能会忍受哪种编译器,除了编写更正确和更好的代码永远不会有坏处,尤其是在样板代码的情况下。
  • 我相信在这种情况下,它是 ++i 还是 i++ 并不重要,因此没有“正确”或“不正确”的方式,甚至没有“更好”的编码方式.在这种情况下,后增量和前增量之间没有区别。
【解决方案2】:

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

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

This is the range-based for loop.

如果您不想更改该功能,您也可以将其声明为string const&amp;(或只是string,但这会导致不必要的复制)。

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 2014-09-23
    相关资源
    最近更新 更多