views:

47

answers:

2

I try to send some struct into STL list;

struct obj {
  int a;
  int b;
}

list < struct obj> mylist;

struct obj a  = { 0, 1}; 
mylist.push_back ( a);

Is there any other way to initialize argument of push_back? For example:

mylist.push_back ( struct obj a ={0, 1});

g++ tells me: expected primary-expression before "struct";

+4  A: 

Define a constructor on struct obj:

obj::obj(int a, int b) // : initializers
{
 // Implementation
}

Use

int val1, val2;
mylist.push_back(obj(val1, val2));

C++0x has new ways to initialize inline. I have seen statements including from Stroustrup that STL containers can be initialized using std::initializer_list<T> in which case it would look something like this in your case where T is obj.

std::list mylist({obj(val1, val2), obj(val3, val4)});
Steve Townsend
A: 

Why don't you give your struct a constructor with a and b as parameters? If you use initializer lists, this should be as fast as your old code and you can say

mylist.push_back(obj(a,b));
fschmitt