0

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";

GManNickG
  • 494,350
  • 52
  • 494
  • 543
rewriter
  • 1
  • 1
  • 1
  • 4
    Why don't you write a constructor? If for some reason you feel you cannot, write a named constructor: `obj make_obj(...)`. – GManNickG Sep 24 '10 at 10:44
  • 1
    Already got some good answers. As an aside - unlike in C, there's no need to keep repeating "struct obj" after you've declared it... C++ works with just `list`, `obj a`. – Tony Delroy Sep 24 '10 at 10:51

2 Answers2

3

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
  • 53,498
  • 9
  • 91
  • 140
0

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
  • 3,478
  • 2
  • 22
  • 24