+ 5
Can someone explain what is going on in this code? I encounter it in C++ challenge and cant understand result.
Challenge question by Yunfei Duan https://code.sololearn.com/cc88TWafFHlj/?ref=app
4 Respostas
+ 4
There's already answers about this quiz, though I'm unable to find them. A vector is, from what I know, a thin wrapper around a dynamic array, with pointers to manage it's internal array. One of said pointers is the _capacity pointer, which points to the position past the block of memory allocated for the array.
When the memory needed exceeds the capacity (calling push_back, for example), a vector will perform operations as follows:
1/ Create a new array with sufficient capacity.
2/ Copy elements from old array to new array.
3/ Add new element to new array.
4/ Delete the old array.
5/ Redirect pointers.
Back to your question:
1/ vector<A> v(4,1) create a temporary A object, which is used by the copy constructor to create 4 elements for the vector. The temporary object is then destroyed, hence count = 1;
2/ v.push_back(1) follows the process above: create a temp-A object and destroy 4 elements in the old array, hence count = 1 + 1 + 4 = 6.
https://code.sololearn.com/c6wSl8PZhP3X/#cpp
+ 4
i absolutely agree with you, Uros Zivkovic i failed this challange too. see my code - i posted it today :)
https://code.sololearn.com/c5uT43WSJ0f0/?ref=app
Nguyễn Văn Hoàng is probably right about the temporary object. i tried in sololearn app and also in the xcode and has got the same result, the creation of the temporary object is clealy visible. i will try in vs tomorrow to see if Microsoft implementation is different.
would be nice if we can rate quizzes too +1 to Yunfei Duan for a good quiz
UPDATE: I checked in MS Visual Studio - the result is the same
+ 2
Thanks!
Very tricky challenge.
:-)
+ 2