Yes there is. See the reserve method. It will request that a vector's capacity be at least enough to contain the number of elements sent as its argument. If you can anticipate an upper bound on the number of items that you want to store in a vector, then you can reserve that amount of space in your vector.
Example from the above link -
// vector::reserve
#include <iostream>
#include <vector>
int main ()
{
std::vector<int>::size_type sz;
std::vector<int> foo;
sz = foo.capacity();
std::cout << "making foo grow:\n";
for (int i=0; i<100; ++i) {
foo.push_back(i);
if (sz!=foo.capacity()) {
sz = foo.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
std::vector<int> bar;
sz = bar.capacity();
bar.reserve(100); // this is the only difference with foo above
std::cout << "making bar grow:\n";
for (int i=0; i<100; ++i) {
bar.push_back(i);
// This block will execute only once
if (sz!=bar.capacity()) {
sz = bar.capacity();
std::cout << "capacity changed: " << sz << '\n';
}
}
return 0;
}
You will see that as you add more elements to the foo
vector, its capacity keeps increasing, but in the second case, since it has already reserved 100 element's space, the capacity is changed only once.
Here is a running example.