Yes - but I can only alter the size by adding or removing elements - which happens by adding the read-in value to the vector. |
No, adding elements happen in one of three ways.
1. When you construct the vector add some elements by using the optional size.
vector<int> vect(10); // Create a vector with 10 initial elements.
2. Use the push_back() or emplace(), insert() methods to add elements. When you use these methods this
happens:
This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity. |
3. Re-size the vector with the resize() function. When using this method the following happens:
If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).
If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.
If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.
Notice that this function changes the actual content of the container by inserting or erasing elements from it. |
Notice how with either push_back() or resize() the vector class modifies the capacity if required.
In order to be able to keep adding stuff (ie altering the size), I need to enlarge the capacity of the vector. Or am I seeing this totally wrong? Please do explain if I am, I'm interested to know. |
Yes you are seeing this wrong. You are not altering the size when you access a vector using the index[] or at() methods you are accessing an existing element. If an element doesn't exist you will either access the vector out of bounds, or if using the at() method throw an out of bounds exception.
To access an element of a vector with either the array notation[] or the at() function the element must exist.
You normally don't need to worry about the capacity, the vector will automatically take care of this.