简体   繁体   English

将std :: list元素插入到std :: list

[英]Inserting a std::list element to std::list

    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? 是否可以在不创建 临时 本地子列表(mylist_)的情况下将子列表插入列表(mylist),以及将类型(sub-list)用作列表(mylist)中的指针会更好,性能?

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. 正如JonM指出的那样,临时文件可能会被任何不错的编译器优化。

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: 诸如Boost.Assign之类的实用工具可简化以下工作:

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

Performance-wise it depends on what you want to do - if you eg expect the lists to be handed around much, use (preferrably smart) pointers to avoid endless copying. 从性能角度看,这取决于您要执行的操作-如果例如,您希望列表多交,请使用(最好是智能的)指针以避免无休止的复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM