C++ 如果使用基于范围的for循环而不是标准for循环,是否可以避免超出范围的错误?
我在对基于范围的for循环进行实验时发现,如果使用基于范围的for循环通过向量进行循环,它会遇到超出范围的错误。如果使用基于范围的for循环,有没有办法避免此错误C++ 如果使用基于范围的for循环而不是标准for循环,是否可以避免超出范围的错误?,c++,for-loop,visual-c++,outofrangeexception,range-based-loop,C++,For Loop,Visual C++,Outofrangeexception,Range Based Loop,我在对基于范围的for循环进行实验时发现,如果使用基于范围的for循环通过向量进行循环,它会遇到超出范围的错误。如果使用基于范围的for循环,有没有办法避免此错误 int main() { vector<int> num{ 1,2,3,4,5 }; for (auto i : num) { cout << num[i] << endl; } } intmain() { 向量num{1,2,3,4,5}; 用于(
int main()
{
vector<int> num{ 1,2,3,4,5 };
for (auto i : num)
{
cout << num[i] << endl;
}
}
intmain()
{
向量num{1,2,3,4,5};
用于(自动i:num)
{
cout这与循环的类型无关。您的循环查看向量num
中的所有值i
,然后打印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));
}
结构索引器{
它,;
It运算符*()常量{返回它;}
void运算符+++(){++it;}
void运算符++(int){++it;}
布尔运算符==(索引器常量&o)常量{返回它==o.it;}
布尔运算符!=(indexer const&o)const{返回它!=o.it;}
};
模板
结构范围{
它是b,e;
它的begin()常量{return b;}
It end()常量{return e;}
};
范围计数(标准::大小开始,标准::大小结束){
std::cout应该是cout Here you docout我倾向于在这里不使用nameI
,正如我们可能期望I
作为索引一样,作为(auto elem:num)
似乎更好。是的,如果您知道自己在做什么,您可以避免“超出范围”。您是否检查了在这种循环中为i
分配了哪些值…?使用向量进行测试,例如{1,2,0,0,0}
非常感谢我看到了代码的问题非常感谢你澄清了我的误解@user253751感谢你给我展示了一个详细的例子@Yakk-Adam Nevraumont
vector<int> num{ 1,2,3,4,5 };
for (auto i : indexes_of(num))
{
cout << num[i] << endl;
}