How do I initialize a stl vector of objects who themselves have non-trivial constructors?

vector c++
initialize vector in constructor
c vector of class constructor
initialization list c++
vector of objects c++
array of objects c++ constructor
vector constructor c++
initialize vector c++

suppose I have the following class:

class MyInteger {
private:
  int n_;
public:
  MyInteger(int n) : n_(n) {};
  // MORE STUFF
};

And suppose this class don't have a default trivial constructor MyInteger(). I must always supply an int to initialize it for some reason. And then suppose that somewhere in my code I need a vector<MyInteger>. How do I initialize each MyInteger component in this vector<>?

I have two situations (probably the solution is the same, but I'll state them anyway), a normal variable inside a function:

int main(){
    vector<MyInteger> foo(10);  //how do I initialize each 
                                //MyInteger field of this vector? 
    doStuff(foo);
}

and as data in a class:

class MyFunClass {
private:
   vector<MyInteger> myVector;

public:
   MyFunClass(int size, int myIntegerValue) : myVector(size) {}; 
   // what do I put here if I need the 
   // initialization to call MyInteger(myIntegerValue) for all 
   // components of myVector?
};

Is it possible to do it just in the initialization list or must I write the initialization by hand in the MyFunClass(int, int) constructor?

This seems so very basic, and yet I somehow missed it inmy book and can't find in the web.

There are many ways to get there. Here are some of them (in no particular order of presence).

Use vector(size_type n, const T& t) constructor. It initializes vector with n copies of t. For example:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values (10, MyInt (20))
    {
    }
};

Push elements into vector one by one. This might be useful when values should be different. For example:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values ()
    {
        values.reserve (10); // Reserve memory not to allocate it 10 times...
        for (int i = 0; i < 10; ++i)
        {
            values.push_back (MyInt (i));
        }
    }
};

Another option is constructor initialization list, if C++0x is an option:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values ({ MyInt (1), MyInt (2), MyInt (3) /* ... */})
    {
    }
};

Of course, there is an option to provide default constructor and/or use something other than std::vector.

Hope it helps.

Constructors, C++ FAQ, What if one member object has to be initialized using another member object? are evil). std::vector lets you decide to use any constructor, not just the default constructor: Or it might happen when two data members are self-referential. initialization and static deinitialization situations, but it has other non-trivial costs. 34 How do I initialize a stl vector of objects who themselves have non-trivial constructors? 30 How can I emulate Go's channels with Haskell? View more network posts →

If the elements of the vector are not default-constructible, then there are certain things you cannot do with the vector. You cannot write this (example 1):

vector<MyInteger> foo(10);

You can, however, write this (example 2):

vector<MyInteger> foo(10, MyInteger(37));

(This only requires a copy constructor.) The second argument is an initializer for the elements of the vector.

In your case, you could also write:

vector<MyInteger> foo(10, 37);

...since MyInteger has a non-explicit constructor taking "int" as argument. So the compiler will cast 37 to MyInteger(37) and give the same result as example 2.

You might want to study the documentation on std::vector.

Constructors (C++), A constructor can initialize an object that has been declared as const , volatile or list is not the same thing as an initializer list of type std::initializer_list<T>.) Rather than copying the vector and its strings, the move constructor For more information about how to write a non-trivial move constructor, see� A code I'm modifying is using tf.get_variable for weight variables, and tf.Variable for bias initialisation. After some searching, it seems that get_variable should always be favoured due to its portability in regards to sharing.

vector<MyInteger> foo(10, MyInteger(MY_INT_VALUE));

MyFunClass(int size, int myIntegerValue) : myVector(size, MyInteger(myIntegerValue)) {}; 

Zero-Trivial Constructors and Destructors, The C++ specification has an explicit definition of a trivial constructor (as well Namely, it means that the object is in a valid state even if the constructor is not run. Some types do need to be initialized, but only to a zero value. array or std::vector) zeroing out the memory is sufficient; there is no need to� 35 How do I initialize a stl vector of objects who themselves have non-trivial constructors? 34 What operators should be declared as friends? 30 How can I emulate Go's channels with Haskell?

Besides all answers which answered the question very well, in a case that your class MyInteger is not copy-constructible, you could use this trick : instead of creating vector< MyInteger>, you could create vector< shared_ptr< MyInteger > >

C++ Tutorial: Constructor - 2020, #include <iostream> using namespace std; class A { public: A(int n = 0) : m(n) { cout A constructor is used to initialize an object after it has been allocated by the new. when the value is not given explicitly, e.g. vector<MyClass>(5); initializes the vector with 5 The process of creating objects in C++ is not a trivial task. 34 How do I initialize a stl vector of objects who themselves have non-trivial constructors? 34 What operators should be declared as friends? 30 How can I emulate Go's channels with Haskell?

Initialization lists can be used without reference to the underlying objects.

#include <string>
#include <vector>
using namespace std;


class Test
{
   public:
   struct NumStr
   {
      int num;
      string str;
   };

   Test(vector<int> v1,vector<NumStr> v2) : _v1(v1),_v2(v2) {}
   vector<int> _v1;
   vector<NumStr> _v2;
};

int main()
{
   Test t={ {1,2,3}, {{1,"one"}, {2,"two"}, {3,"three"}} };
   cout << t._v1[1] << " " << t._v2[1].num << " " << t._v2[1].str << endl;
   return 0;
}

output: 2 2 two

P0593R5: Implicit creation of objects for low-level object , Types with only a trivial default constructor may be suitable for Consider this program that attempts to implement a type like std :: vector (with many details object creation itself typically has no effect on the physical machine, If we add a fourth push_back call to the program prior to the initialization of n� MODULE: vector SUMMARY: Template class for dynamic-sized vectors. The declaration Vec<T> v; creates a zero-length vector. To grow this vector to length n, execute v.SetLength(n) This causes space to be allocated for (at least) n elements, and also causes the default constructor for T to be called to initialize these elements.

Modern C++ Features, If you have additional constructors and still want a default constructor, declare it as struct Trivial { int k; private: int l; }; struct Problematic { vector<int> vi; int u; Trivial t; A default constructed object of type `Problematic` is, in fact, Only `vi` has a nontrivial default constructor and therefore will be initialized� If our object requires non-trivial initialization, consider using a factory function or Init() method. Default Constructors We must define a default constructor if our class defines member variables and has no other constructors.

C++ FQA Lite: Constructors, FAQ: A constructor initializes an object given a chunk of memory having arbitrary And you should use std::vector anyway since arrays are evil. on the stack, for example, so if you want one, you'll have to write it yourself. Consider the reasons to avoid instantiating global objects with non-trivial constructors (ones that do� 2) Initialize variables in the initializer list in the same order in which they are declared in your class. This isn’t strictly required so long as the prior recommendation has been followed, but your compiler may give you a warning if you don’t do so and you have all warnings turned on. Summary

Copy Constructor, If a class definition does not include a constructor, MATLAB will initialize the default values provided in the property definition block, or to empty vectors. MATLAB does not have a copy constructor, but it would be possible to write a In addition, STL iterators and function objects are designed to be passed by value. Q&A for Ubuntu users and developers. Stack Exchange Network. Stack Exchange network consists of 177 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Comments
  • Should the integer be the same for all instances inside the vector?
  • It's good enough. I just want to learn how to initialize the vector. The real code where this doubt appeared is not exactly this. I just wanted a simple code with the same problem.
  • In my real code I have a vector of graphs and a class which is a collection of graphs, and I'm using a vector<Graph> as a container. The problem is that the number of graphs in the collection must be the same as the size of the Graphs, so I must pass to the Graph constructor the same int I pass to the vector constructor.
  • Hum! Does g++ support C++0x yet?
  • Now that it's 2017, I'd probably start with the C++11 initialization example.
  • Alternatively, in the member initialization list of MyStuff's default ctor, you can use uniform initialization like so: MyStuff () : values{ {1}, {2}, {3} } {}