c++ vector使用下标赋值出错

有以下程序

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

int main()
{
    vector<int> v;
    v[0] = 1;
    return 0;
}

运行会出现内存非法操作的错误。症结在于“v[0] = 1”一句。

一开始vector为空时,不能对其进行下标赋值。而要用push_back().

以下程序

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

int main()
{
    vector<int> v;
    v.push_back(1);
    v[3] = 2;
    cout << v[0] << " " << v[3] << endl;
    return 0;
}

输出:1 2


注:以上程序在winXP系统中,使用GNU GCC compiler进行编译

原文地址:https://www.cnblogs.com/cszlg/p/2910446.html