如何解决如果你使用基于范围的 for 循环而不是标准的 for 循环,你能避免超出范围的错误吗?
我正在尝试使用 基于范围 的 for 循环发现,如果您使用基于范围的 for 循环来循环遍历一个向量,它会遇到 超出范围 错误是如果您使用 基于范围的 for 循环
,有什么方法可以避免此错误int main()
{
vector<int> num{ 1,2,3,4,5 };
for (auto i : num)
{
cout << num[i] << endl;
}
}
解决方法
这与循环的类型无关。您的循环查看向量 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;
}
您的问题是将索引误认为元素的向量。 Range-for 返回元素。 indexes_of
使其返回相关容器的索引。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。