Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如果使用基于范围的for循环而不是标准for循环,是否可以避免超出范围的错误?_C++_For Loop_Visual C++_Outofrangeexception_Range Based Loop - Fatal编程技术网

C++ 如果使用基于范围的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}; 用于(

我在对基于范围的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};
用于(自动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 do
cout我倾向于在这里不使用name
I
,正如我们可能期望
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;
}