lundi 9 septembre 2019

strange behaviour when vector elemnts are set using indexing

Trying to copy all elements from one vector to another using indexing as shown in code snippet. As far as I understand, setting/getting an element in vector using index(I'm aware about "at" and its benefits) is allowed in C++.

If I set an element in vector a using index, it works as expected. For vector b also, If push_back is used, it works as expected.

int main() 
{   
vector<int> a{1,3,6,10,56,9};
vector<int> b;
b.reserve(a.size());
cout << "1. a[2]: " << a[2] << endl;
a[2] = 100;
cout << "2. a[2]: " << a[2] << endl;
for(int i=0; i<a.size(); ++i)
{
    b[i] = a[i];
}
cout << "1. b.size() : " << b.size() << endl;


for(int i=0; i<a.size(); ++i)
{
    b.push_back(a[i]);
}
cout << "2. b.size() : " << b.size() << endl;
return 0;
}

I'm finding it difficult to understand this behaviour of vector.

Note: I know this is not a suggested way of copying vector as we have multiple other options which both convenient and effective.

output:

1. a[2]: 6
2. a[2]: 100
1. b.size() : 0
2. b.size() : 6

Aucun commentaire:

Enregistrer un commentaire