Pushing back a new struct on a list/vector

E

eriwik

Consider this:

#inlcude <list>

struct elem {
int col;
int val;
};

int main() {
std::list<elem> l;

l.push_back(elem e={1,1}); // Error

elem e = {1,1};
l.push_back(e); // OK

return 0;
}

Is there any way to make the non-working line work without adding a
constructor to elem? What I want to do is to create an anonymous struct
and pass it as an argument to a function using initialization. It's not
particulary important, it's just been bugging me for some time now.
 
A

Alf P. Steinbach

* (e-mail address removed):
Consider this:

#inlcude <list>

struct elem {
int col;
int val;
};

int main() {
std::list<elem> l;

l.push_back(elem e={1,1}); // Error

elem e = {1,1};
l.push_back(e); // OK

return 0;
}

Is there any way to make the non-working line work without adding a
constructor to elem?

No. And why would you want to?

What I want to do is to create an anonymous struct
and pass it as an argument to a function using initialization.

You might consider using std::pair, or (not yet standard) std::tr1::tuple.
 
M

mimi

"(e-mail address removed) 写é“:
"
Consider this:

#inlcude <list>

struct elem {
int col;
int val;
};

int main() {
std::list<elem> l;

l.push_back(elem e={1,1}); // Error

elem e = {1,1};
l.push_back(e); // OK

return 0;
}

Is there any way to make the non-working line work without adding a
constructor to elem?
I think adding a constructor is required. You could use std::pair, but
it provides a constructor also, not by you, but by the STL.
 
D

David Harmon

On 22 Nov 2006 01:07:20 -0800 in comp.lang.c++,
Is there any way to make the non-working line work without adding a
constructor to elem? What I want to do is to create an anonymous struct
and pass it as an argument to a function using initialization.

Sorry, no way to do that, but you can make it nearly anonymous by
limiting the scope of the very short-lived name.

{elem e = {1,1}; l.push_back(e);}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top