I'm trying to figure out how does a vector adds more objects after it has already "Created" some:
int *ptr;
ptr = new int;
How after using that, can you add more objects to that pointer? (make it an array). Thanks!
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:
int *ptr;
ptr = new int;
How after using that, can you add more objects to that pointer? (make it an array). Thanks!
Most implementations start off with a small array, and whenever it reaches its capacity, a new array of double the size is allocated and the old elements are copied to the new array.
reserve()).As with most STL containers it uses an external allocator to actually allocate the memory. This is the second template parameter to vector.
It uses placement-new to create the objects into the memory.
For adding more objects when it has run out of memory it must allocate a bigger amount. If the underlying type is POD it can just realloc, but if not it must move them with the object's operator=.
realloc()?. So malloc() is not obsolete in c++, and new is unavoidable only when the object to allocate is not POD. Can you point me to a good document where they explain why there is no renew operator in c++?std::vector removes the need completely but I was just curious, thank you for your response.1. Build an array.
2. copy *ptr into it.
3. swap ptrs.
4. delete the temp.
There you go, you now have "resized" your ptr.
A vector keeps track of two bits of information.
If adding an element does not cause it to exceed its capacity, then there is no problem. It simply adds the new element.
If the capacity will be exceeded, then it will calculate a new capacity (usually between 1.5 and 2 times the current capacity) and copy all elements to the new array. This is why iterators are invalidated after adding an item to a vector. They may be referring to the old (now freed) array.
Vector can resize because it a class. It hides data inside an object and you cannot see its internal structure directly. You just work with its public interface. It can allocate a new larger array a copy data to it without you seeing it.
You cannot do this with int*, because you have no class here, no place to hide real implementation from user.
int* arr = new int[n];, but it'd be a pain to track logical size vs. allocated size yourself.