Search code examples
c++c++11vectorargumentsinitializer-list

how to create a vector as an argument


I have an object that takes a vector as one of it's constructor arguments. I will have around 1000 of these objects (contained in a vector) in each of 12 files by the time I'm finished, and I've been experimenting with layout. The best way I can find to work it is to create all arguments within the object definition.

Here is a basic version of the struct:

struct MyObject {
  MyObject (vector<int>);
  vector<int> paraList;
}

So my object definition will look something like this:

MyObject object1 ( {0, 1, 2} );
MyObject object2 ( {0, 3, 1} );
MyObject object3 ( {5, 7, 5, 6} );
MyObject object4 ( {4} );

This works, but what I'd really like to do is construct the objects within the vector definitions instead. Like so:

vector<MyObject> objectList {
  ( {0, 1, 2} ), 
  ( {0, 3, 1} ),
  ( {5, 7, 5, 6} ),
  ( {4} )  
};

It feels like that should work, but it doesn't. I get:

error: expected primary-expression before '{' token
error: expected ')' before '{' token
error: expected '}' before ')' token

I feel like my syntax would be correct if this were possible, so is what I'm trying to do not possible?

EDIT:

Sorry, besides a few spelling mistakes I'm not sure why this is off topic. I've been reading through the rules and I'm still not sure, could you please comment or PM me what I've done wrong so I can avoid it in future? That's not meant to be moany, just want to make sure I get it right.


Solution

  • You should do it like this:

    std::vector<MyObject> objectList {{{0, 1, 2}} , {{0, 3, 1}} , {{5, 7, 5, 6}} ,{{4}}};
    

    Live Demo