微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果你使用基于范围的 for 循环而不是标准的 for 循环,你能避免超出范围的错误吗?

如何解决如果你使用基于范围的 for 循环而不是标准的 for 循环,你能避免超出范围的错误吗?

我正在尝试使用 基于范围 的 for 循环发现,如果您使用基于范围的 for 循环来循环遍历一个向量,它会遇到 超出范围 错误是如果您使用 基于范围的 for 循环

,有什么方法可以避免此错误
int main()
{
    vector<int> num{ 1,2,3,4,5 };
    for (auto i : num)
    {
        cout << num[i] << endl;
    }
}

显示这个错误

enter image description here

解决方法

这与循环的类型无关。您的循环查看向量 i 内的所有值 num,然后打印 num[i]。其中之一是 5,所以它打印 num[5]。但是 num 有 5 个元素,所以它们最多只能到 num[4]。超出范围。

,
template<class It>
struct indexer {
  It it;
  It operator*()const{return it;}
  void operator++(){++it;}
  void operator++(int){++it;}
  bool operator==(indexer const& o)const{ return it == o.it; }
  bool operator!=(indexer const& o)const{ return it != o.it; }
};
template<class It>
struct range {
  It b,e;
  It begin()const{return b;}
  It end()const{return e;}
};
range<indexer<std::size_t>> counting( std::size_t begin,std::size_t end ) {
  std::cout << begin << "->" << end << "\n";
  return {{begin},{end}};
}

template<class X>
auto indexes_of( X const& x ) {
  using std::size;
  return counting(0,size(x));
}

现在我可以让你的代码按照你的想法去做:

vector<int> num{ 1,2,3,4,5 };
for (auto i : indexes_of(num))
{
    cout << num[i] << endl;
}

Live example

您的问题是将索引误认为元素的向量。 Range-for 返回元素。 indexes_of 使其返回相关容器的索引。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?