jeudi 29 janvier 2015

Do vector.emplace_back() and vector.push_back() do the same thing?

So I was trying to add integers onto the back of my vector and mistakenly thought push_back() added the new data onto the front of the vector (aka vector[0]). I did a test in Xcode and tested push_back() against emplace_back() and got the same results. I thought they were different, but this makes me think that maybe they do the same thing. If this is so, why does vector have the different methods?


Here's my code in case I was doing:



#include <vector>
#include <iostream>

using namespace std ;

int main(int argc, const char * argv[])
{
// for push_back
vector<int> push;
push.push_back(1);
push.push_back(2);
push.push_back(3);
push.push_back(4);
push.push_back(5);
push.push_back(6);
//display push_back
for (int i = 0; i < push.size(); i++) {
cout << "push[" << i << "]: " << push[i] << endl;
}
// distance between the two funcitons
cout << endl << endl;

vector<int> emplace;
emplace.emplace_back(1);
emplace.emplace_back(2);
emplace.emplace_back(3);
emplace.emplace_back(4);
emplace.emplace_back(5);
emplace.emplace_back(6);

//display emplace_back
for (int i = 0; i < emplace.size(); i++) {
cout << "emplace[" << i << "]: " << emplace[i] << endl;
}
return 0;
}


The return was:



push[0]: 1
push[1]: 2
push[2]: 3
push[3]: 4
push[4]: 5
push[5]: 6


emplace[0]: 1
emplace[1]: 2
emplace[2]: 3
emplace[3]: 4
emplace[4]: 5
emplace[5]: 6


I know this is a super easy question, but I just want to make sure I am not doing something stupidly wrong and misunderstanding the abilities of the vector class.


Aucun commentaire:

Enregistrer un commentaire