How to determine the vector?

From this answer :

In one place where you might run into a performance issue, you don't need to define the vector correctly.

So, how to correctly define a vector when it is a property of a class? Is there a (best) way to set the capacity of a vector (upon initialization)?

+4
source share
2 answers

Yes there is. See reserve method. He will ask that the vector capacity be at least sufficient to contain the number of elements sent as an argument. If you can foresee the upper bound on the number of elements that you want to keep in the vector, you can reserve this amount of space in your vector.

An example from the above link is

// 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 additional elements are added to the vector foo its capacity increases, but in the second case, since it has already reserved 100 element spaces, the capacity changes only once.

Here is an example.

+2
source

Given that a class is assigned a value during the constructor, the smart thing would be to preserve the initial size of the vector. Inefficiency occurs when the user is constantly expanding the size of the vector, rather than setting the base length of the vector to start with.

 //consider the vector reads in chars from a string VecClass::VecCalss(char * str) { size_t LEN = strlen(str); Vect = std::vector<char>(LEN, '\0'); //start with the initial size of the char } 

setting the initial size reduces the number of times it takes for the vector to expand in the program.

EDIT: or the backup method will do roughly the same thing, I never knew that there was a backup function (quite convenient!).

+1
source

All Articles