dimanche 17 février 2019

What's the difference between the following ways of adding elements to a c++ vector [duplicate]

Snippet1: The following snippet prints out 0 1 but returns an empty vector.

vector<int> trial() {
    vector<int> ret;
    ret.reserve(2);
    ret[0] = 0;
    ret[1] = 1;
    cout << ret[0] << " " << ret[1] << "\n";
    return ret;
}

Snippet 2: The following snippet prints out 0 1 and returns a vector contains {0,1}.

vector<int> trial() {
    vector<int> ret;
    ret.push_back(0);
    ret.push_back(1);
    cout << ret[0] << " " << ret[1] << "\n";
    return ret;
}

Why doesn't snippet 1 work like snippet 2. If I am reserving memory and adding values to the vector.

Aucun commentaire:

Enregistrer un commentaire