vector下标出C 中的奇怪行为

vector subscript out of range error strange behavior in C++

本文关键字:下标 vector      更新时间:2023-10-16

我开始学习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

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

行为并不奇怪。这就是应该发生的事情,因为std :: vector不会执行大小检查" []"。

所以,您基本上是从V1 [10]。

获得垃圾