Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stl vector and c++: how to .resize without a default constructor?

How do I tell STL, specifically for the method resize() in vector, to initialize objects with a constructor other than default, and with which parameters?

For example:

class something {     int a;     something (int value); }  std::vector<something> many_things;  many_things.resize (20); 

More generally, how do I force STL to use my constructor when it needs to create objects, and pass parameters to that constructor?

In my case adding a default constructor is not an option, and I'd prefer not to use an array of pointers to solve the problem.

like image 700
conejoroy Avatar asked Nov 06 '09 12:11

conejoroy


People also ask

Does a vector have a default constructor?

The default vector constructor takes no arguments, creates a new instance of that vector. The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c. All of these constructors run in linear time except the first, which runs in constant time.

What happens if you use the default copy constructor for vector?

The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.

How do you add a vector to a constructor?

Begin Declare a class named as vector. Declare vec of vector type. Declare a constructor of vector class. Pass a vector object v as a parameter to the constructor.


2 Answers

Use the 2-argument overload: many_things.resize(20, something(5));

like image 184
MSalters Avatar answered Oct 04 '22 16:10

MSalters


I can think of a solution, but iwarn you, it's rather ugly. I don't know why you do not want to add a default constructor, but if you just want to prevent users of the class to create unintialized instances, you can just make the default constructor private and declare the appropriate vector class a friend :

class Foo { public:    Foo( int x ) : num( x ) {}     int GetX( ) { return num; } private:    friend class std::vector< Foo >;     int num;    Foo( ) : num( 10 ) {} }; 

This is ugly for several reasons, mostly because it only works for one container type. There is no other way, because STL containers simply require their items to be default constructible.

like image 32
Björn Pollex Avatar answered Oct 04 '22 15:10

Björn Pollex