如何将c++列表与自身进行快速合并
How to perform fast merging c++ list with itself
假设我有一个包含一些整数的列表,我需要快速将其与自身合并:例如,我有{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),但这里不需要它。显然,复制一个大列表仍然需要时间,但这是不可避免的。
相关文章:
- 使用C++程序合并排序没有得到正确的输出
- 用于合并排序的合并函数
- 在声明中合并两个常量"std::set"(不是在运行时)
- 如何将一个数组值合并为一个整数c++
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 将向量的 N 段合并到位C++
- 在C++中合并两个库
- 以迭代方式合并标准::unordered_map
- 无法合并生成操作.. 先决条件不同
- 合并排序不排序自创建数组类 c++
- 合并文本文件不同行中的重复项
- 找不到标识符合并
- 仅在大型阵列上出现合并排序分段错误
- C++ 合并字符串以'system'函数错误
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- C++合并排序可视化工具
- 合并一组模板专用化
- 没有输出的合并排序我做错了什么?
- 字符串上的合并排序上的 Seg 错误
- 使用向量在 c++ 中合并排序实现