Can someone explain what is going on in this code? I encounter it in C++ challenge and cant understand result. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

22nd Sep 2018, 2:19 PM
Uros Zivkovic
Uros Zivkovic - avatar
4 Answers
+ 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
22nd Sep 2018, 2:46 PM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 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
30th Sep 2018, 10:06 AM
wave rider
+ 2
Thanks! Very tricky challenge. :-)
22nd Sep 2018, 2:52 PM
Uros Zivkovic
Uros Zivkovic - avatar