向量下标超出范围错误C ++中的奇怪行为

时间:2018-02-14 18:09:36

标签: c++ c++11

我开始学习C ++,所以我的问题的答案可能对你很明显,但我真的很困惑。我希望程序在访问超出范围的索引时会崩溃,但是程序运行得很好。这是代码。

    #include <iostream>
    #include <typeinfo>
    #include <string>
    #include <vector>

    using namespace std;

    int main() {
        int x;
        vector<int> v1;

        while (cin >> x) {
            v1.push_back(x);
        }

        cout << "out of bound: " << v1[10] << endl;
    return 0;
}

这是输出:

1 2 3
out of bound: 0

1 个答案:

答案 0 :(得分:-3)

v1中有3个元素,意味着没有v1 [10],只有v1 [0]到v1 [2]。

行为不是,很奇怪。那是应该发生的事情,因为std :: vector不会对&#39; []&#39;进行大小检查。

所以,你基本上是从v1 [10]获得垃圾。