如何迭代一个常量向量? [英] How do I iterate over a Constant Vector?

查看:212
本文介绍了如何迭代一个常量向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有一个字段名的学生的向量。

I have a vector of Student which has a field name.

我要遍历向量。

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

这在C ++中显然是违法的。

This is apparently illegal in C++.

请帮助。

推荐答案

选项: const_iterator 和索引(C ++ 11中的range-for)

You have two (three in C++11) options: const_iterators and indexes (+ "range-for" in C++11)

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

您应该优先使用!= ,而不是< 与迭代器 - 后者不能与所有迭代器,前者将工作。使用前者,你甚至可以使代码更通用(所以你甚至可以改变容器类型,而不用接触循环)

You should prefer using != instead of < with iterators - the latter does not work with all iterators, the former will. With the former you can even make the code more generic (so that you could even change the container type without touching the loop)

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

这篇关于如何迭代一个常量向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆