tags:

views:

102

answers:

1
    std::list <std::list <int>> mylist;
    std::list <int> mylist_;

    mylist_.push_back(0);
    mylist.push_back(mylist_);

is it possible to insert a sub-list into the list (mylist) without creating the temporary local sub-list (mylist_) and would it be better to use the type (sub-list) as pointer in list (mylist) in terms of performance?

+3  A: 

You can't really do it without temporaries, but you can do it more concisely:

mylist.push_back(std::list<int>(1, 0)); // insert 1 element with value 0

As JonM notes, the temporary will probably be optimized away by any decent compiler.

You can use arrays:

int vals[] = { 1, 2, 3, 4 };
mylist.push_back(std::list<int>(vals, vals+sizeof(vals)/sizeof(vals[0])));

Utilities like Boost.Assign ease that:

mylist.push_back(boost::assign::list_of(1)(2)(3));

Performance-wise it depends on what you want to do - if you e.g. expect the lists to be handed around much, use (preferrably smart) pointers to avoid endless copying.

Georg Fritzsche
It might be good to note performance-wise that your first method will result in the compiler probably optimizing out the creation of any temporary list.
JonM
Indeed, i added that.
Georg Fritzsche