+ 3
Intern work of push_back()?
So, I was making my own, very simple vector class to show its inner working. But now I wonder how the push_back() function actually works - more precisely how it knows whether to use the existing space - e.g. because vector's capacity is 5, but only 3 elements are inside - or to resize to [Size + 1], assigning the value to the newly created space. Can someone help me out there with an explanation (code below)? https://code.sololearn.com/cAwjFIJU2Mk6/?ref=app
4 Respostas
+ 6
I typed up some code (with comments), as I think it's probably easier to understand:
https://code.sololearn.com/cJiIZqeRKjcE/#cpp
Only showing minimal stuff.
You should keep a capacity variable that keeps track of the actual maximum vector size.
Then when you try to push_back data you simply check if the current size is equal to the maximum capacity, if so reallocate with a new, bigger capacity and then add the new data.
However don't increase the new cap to cap + 1 as this causes for too many allocations.
Ask away if you have any more questions :)
+ 10
// only exists for reference purposes.
// not to be taken as a proper answer.
I doubt there would be a case wherein the size of the vector is 5 but with only 3 elements inside. A vector would always have its size equal to the number of elements it currently holds. Say for example, if you have three elements
1 2 3
and you do MyVec.resize(5), it would contain
1 2 3 0 0
doing MyVec.push_back(4) would result in
1 2 3 0 0 4
I'll check shortly if this reflects its behaviour. Try running:
std::vector<int> obj = {1,2,3};
obj.resize(5);
obj.push_back(4);
for(int i : obj) std::cout << i;
+ 9
Yes there is.. these days i was studying exactly this one.
I checked stackoverflow and it seems vector can allocate more space than needed for optimization, this is the internal behaviuor, but abstraction dosent show you class triks.. i think.
+ 3
@Hatsy Thanks for your answer, you are of course right, because the size is the number of elements currently stored in the vector. My question was more about the additional capacity vectors have for optimization, as explained by @AZTECCO.
@Dennis With what you gave me, I should be able to type the rest on my own, e.g. remaking the structure + insert() and other functions.
Also big thanks for the very detailed code example!
So no more questions now...
But I'll eventually come up with new ones ;)