Originally Posted by
std10093
How to set the size of the vector in the constructor?
Use the initialiser list:
Code:
#include <vector>
class Foo {
public:
Foo() : test(100) {}
private:
std::vector<int> test;
};
int main()
{
Foo foo;
return 0;
}
Note that this actually creates 100 elements, so if you are dealing with objects that are expensive to default construct, calling reserve in the constructor body might be better as it will reserve space for, but not actually create, those elements. Of course, you then cannot access those elements until they have been created, e.g., with push_back.
Originally Posted by
std10093
But what really made me worry is this: shrink_to_fit, which actually implies that the resize will not reduce the size of my vector? It is a C+11 standard and want to be able to run with a non compatible to C+11 compiler.
No, resize will indeed reduce the size of the vector, as the name implies. However, it might not free up the space for the elements that are erased. shrink_to_fit is intended for that purpose. If you cannot use shrink_to_fit due to pre-C++11 compatibility, then an alternative is to create a copy of the vector, then swap the old vector with the new vector.