如何迭代常量向量?

unj*_*nj2 46 c++ visual-c++

我有一个学生的矢量,有一个字段名称.

我想迭代矢量.

void print(const vector<Student>& students)
    {
    vector<Student>::iterator it;
    for(it = students.begin(); it < students.end(); it++)
        {
            cout << it->name << endl;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这在C++中显然是非法的.

请帮忙.

eq-*_*eq- 64

你有两个(C++ 11中有三个)选项:const_iterators和索引(+ C++ 11中的"range-for")

void func(const std::vector<type>& vec) {
  std::vector<type>::const_iterator iter;
  for (iter = vec.begin(); iter != vec.end(); ++iter)
    // do something with *iter

  /* or
  for (size_t index = 0; index != vec.size(); ++index)
    // do something with vec[index]

  // as of C++11
  for (const auto& item: vec)
    // do something with item
  */
}
Run Code Online (Sandbox Code Playgroud)

您应该更喜欢使用!=而不是<使用迭代器 - 后者不适用于所有迭代器,前者将使用.使用前者,您甚至可以使代码更通用(这样您甚至可以在不触及循环的情况下更改容器类型)

template<typename Container>
void func(const Container& container) {
  typename Container::const_iterator iter;
  for (iter = container.begin(); iter != container.end(); ++iter)
    // work with *iter
}
Run Code Online (Sandbox Code Playgroud)

  • @kunjaan:只有随机访问迭代器支持排序(`<`),其他人则不支持.例如,std :: list具有双向迭代器,只能进行相等性比较. (4认同)

Fre*_*Foo 19

const_iterator改用.一个iterator允许修改vector,所以你不能从const容器中获取一个.

此外,编写此循环的惯用方法是使用it != students.end()而不是<(尽管这应该适用于a vector).

  • ...但是如果您决定改为使用`list`或类似的东西,那么您的代码将无效.所以使用`!=`表格. (2认同)

Shi*_*hah 5

C ++ 11样式:

void print(const vector<Student>& students) {
    for(auto const& student : students) {
            cout << student.name << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我说被低估但拼错了一个 r。反正不说不相关。 (2认同)