简体   繁体   English

Visual Studio / C ++:反向迭代器编译,但在运行时引发错误

[英]Visual Studio/C++: Reverse iterator compiles, but throws an error at runtime

I'm taking a course to learn C++ and as a part of this course, some example code was provided (which works in the instructor's video). 我正在学习一门学习C ++的课程,并且作为该课程的一部分,提供了一些示例代码(可在讲师的视频中使用)。 However, one part of a program is giving me issue. 但是,程序的一部分给了我问题。

And searching SO , I realize I can use a reverse iterator; 然后搜索SO ,我意识到我可以使用反向迭代器。 however, I was hoping someone could explain why the code below throws a runtime error in VS C++, but not in Linux (with g++). 但是,我希望有人能解释为什么下面的代码在VS C ++中引发运行时错误,而在Linux(使用g ++)中却没有。

#include <iostream>
#include <vector>
using namespace std;

int main( int argc, char ** argv ) {
        vector<int> vi1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        vector<int>::iterator it;   // vector iterator

        // bidirectional iterator -- iterate forward or backward
        // allows it--
        cout << "bidirectional iterator:" << endl;
    for(auto it = vi1.end() - 1; it >= vi1.begin(); --it) {
                cout << *it << " ";
        }
        cout << endl;

        return 0;
}

Edit: 编辑:

Added error message 添加了错误信息

在此处输入图片说明

During the last iteration of the loop, it is decremented to be before the start of its container, vi1 . 在循环的最后一次迭代期间, it递减到其容器vi1开始之前。 This results in an out-of-bounds iterator. 这将导致越界迭代器。 The debug build with Visual Studio will detect this and show you the error you get. 使用Visual Studio的调试版本将检测到此错误,并向您显示错误。 A release build will not detect this problem. 发布版本不会检测到此问题。

While it doesn't result in a crash in this instance, decrementing an iterator before the first element can cause crashes or other Undefined Behavior with other container types. 尽管在这种情况下它不会导致崩溃,但是在第一个元素开始递减迭代器可能会导致崩溃或其他容器类型的其他未定义行为。 Trying to dereference such an iterator is also Undefined Behavior. 尝试取消引用此类迭代器也是未定义行为。

rbegin() and rend() are the standard library methods that return reverse iterators. rbegin()rend()是返回反向迭代器的标准库方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM