如何将c++列表与自身进行快速合并

How to perform fast merging c++ list with itself

本文关键字:合并 c++ 列表      更新时间:2023-10-16

假设我有一个包含一些整数的列表,我需要快速将其与自身合并:例如,我有{1,2,3}。在该过程之后,我希望列表为{1,2,3,1,2,3}这些版本可以做到这一点,但当列表大小足够大(10^6)时速度太慢

    list< int > l;    //l got some integers here         
    list< int > l_copy = l;
    while (l_copy.size() > 0)
    {
        l.push_back(l_copy.front());
        l_copy.pop_front();
    }
    //another version but still slow i think
    size_t size = l.size();
    for (list<int>::iterator it = l.begin(); size--; ++it)
    {
        l.push_back(*it);
    }

有没有其他方法可以做到这一点,但速度要快得多?感谢

您可以使用std::list::splice进行以下操作:

list<int> l;
list<int> l_copy = l;    
l.splice (l.end(), l_copy);

该版本的splice根据标准保证在恒定时间内工作(n4296中的§23.3.5.5/6)。它的工作原理是将第一个列表的末尾指向另一个列表的开头。还有另一个版本的splice,它使用迭代器范围O(n),但这里不需要它。显然,复制一个大列表仍然需要时间,但这是不可避免的。