I'm going to give you some code, but make sure you think about what it's doing. Also, it won't be plug-and-play code either. I think learning this idea and implementing it as you see fit will be much better, and knowing these concepts in the future (rather than copy-pasting someone's code) will help you avoid issues later.
Conceptually I'll explain how a couple methods from the vector class work, and then give an example of how you might use them. The beauty of a vector is that it's a dynamic array that is also a class. It benefits both from being able to dynamically adjust its size during program runtime (whereas a normal array is statically defined at initialization of the variable) as well as having access to a slew of useful methods.
.size()
returns the number of elements currently in the vector that's calling the method.
.capacity()
returns the total number of elements that can currently be contained within the vector that's calling the method.
Example:
Say you have
words
, which is like the vector in your code. When it's defined it has a certain
capacity as well as a current
size. Using these methods can be incredibly useful to determine whether or not your vector is getting "full" and when you should allocate more memory to it.
You can then use logic to perform an operation to adjust the capacity if need be. Forgive my previous post, but resize() is not the method you would want to use in this case, since resize() directly affects the vectors
size (i.e. the current number of elements in it right now) and not its overall capacity. The
capacity is what we care about since we're trying to make sure that the program isn't trying to add elements to a vector that's "full". If you want to think of a vector as a glass of water, adjusting the capacity to fit more elements is basically like increasing the size of the glass to fit more water. Instead we would want to use the reserve() method (found at
http://www.cplusplus.com/reference/vector/vector/reserve/).
Some example code to support this idea is as follows:
1 2 3 4
|
if (words.size() == words.capacity())
{
words.reserve(words.size() * 2);
}
|
This code checks to see if the size of the vector named
words
is equal to its defined capacity. If the logic operator == evaluates that statement to true, then the capacity of the vector
words
is altered to a new value dependent on the parameter of the reserve() method. I used
words.size() * 2
as the new value as this gives plenty of new room for the vector and is also more robust because it depends on its current variable size. You could also use something like
words.reserve(words.size() + 10)
or something similar if you'd rather keep the size of the vector down for performance sake. For your case though, I don't think it matters.