[STL] list merge 函数
2015-09-04 16:54
274 查看
STL list容器由于采用了双向迭代器,不支持随机访问,所以标准库的merge(), sort()等功能函数都不适用,list单独实现了merge(),sort()等函数。首先说一下merge() (以void merge(list& __x); 为例)
按照函数声明的注释:
/**
* @brief Merge sorted lists.
* @param x Sorted list to merge.
*
* Assumes that both @a x and this list are sorted according to
* operator<(). Merges elements of @a x into this list in
* sorted order, leaving @a x empty when complete. Elements in
* this list precede elements in @a x that are equal.
*/
它应该合并两个有序的list, 故做此验证:
#include <iostream>
#include <list>
#include <iomanip>
using namespace std;
int main()
{
// 有序数据
int A1[]={1,2,3,4,5,6};
int A2[]={2,4,6,8,9,10};
// 无序数据
int A3[]={1,2,3,4,6,9};
int A4[]={5,6,7,8,9,2};
//有序链表
list<int> iL1(A1, A1+6);
list<int> iL2(A2, A2+6);
//无序链表
list<int> iL3(A3, A3+6);
list<int> iL4(A4, A4+6);
iL1.merge(iL2);
iL3.merge(iL4);
list<int>::iterator it = iL1.begin();
while(it!=iL1.end())
{
cout<<setw(3)<<*it++;
}
cout<<endl;
it=iL3.begin();
while(it!=iL3.end())
{
cout<<setw(3)<<*it++;
}
cout<<endl;
system("pause");
return 0;
}
输出为:
1 2 2 3 4 4 5 6 6 8 9 10
1 2 3 4 5 6 6 7 8 9 9 2
可以看到合并的第一个list仍是有序的,第二个最后一个元素是2,无序。
得到结论:
当源list均有序时,得到的list仍是有序的
当源list无序时,得到的list不能保证有序,之所以这样说是因为,当list1的前两个元素即表现出无序时,合并后的结果将是直接把list2接到list1的后面。。
转自:/article/11174699.html
按照函数声明的注释:
/**
* @brief Merge sorted lists.
* @param x Sorted list to merge.
*
* Assumes that both @a x and this list are sorted according to
* operator<(). Merges elements of @a x into this list in
* sorted order, leaving @a x empty when complete. Elements in
* this list precede elements in @a x that are equal.
*/
它应该合并两个有序的list, 故做此验证:
#include <iostream>
#include <list>
#include <iomanip>
using namespace std;
int main()
{
// 有序数据
int A1[]={1,2,3,4,5,6};
int A2[]={2,4,6,8,9,10};
// 无序数据
int A3[]={1,2,3,4,6,9};
int A4[]={5,6,7,8,9,2};
//有序链表
list<int> iL1(A1, A1+6);
list<int> iL2(A2, A2+6);
//无序链表
list<int> iL3(A3, A3+6);
list<int> iL4(A4, A4+6);
iL1.merge(iL2);
iL3.merge(iL4);
list<int>::iterator it = iL1.begin();
while(it!=iL1.end())
{
cout<<setw(3)<<*it++;
}
cout<<endl;
it=iL3.begin();
while(it!=iL3.end())
{
cout<<setw(3)<<*it++;
}
cout<<endl;
system("pause");
return 0;
}
输出为:
1 2 2 3 4 4 5 6 6 8 9 10
1 2 3 4 5 6 6 7 8 9 9 2
可以看到合并的第一个list仍是有序的,第二个最后一个元素是2,无序。
得到结论:
当源list均有序时,得到的list仍是有序的
当源list无序时,得到的list不能保证有序,之所以这样说是因为,当list1的前两个元素即表现出无序时,合并后的结果将是直接把list2接到list1的后面。。
转自:/article/11174699.html
相关文章推荐
- 操作符重载
- Weird Clock
- 排序小节
- 20.状态模式
- 路由追踪tracert命令
- XCode Build Settings中几种Search Paths
- Processing 教程(5) - 媒体(图片,音频,视频) 文本再次学习
- XCode Build Settings中几种Search Paths
- Android实例-为程序创建快捷方式(未测试)
- 第42讲:Scala中泛型类、泛型函数、泛型在Spark中的广泛应用
- 欧拉工程第60题:Prime pair sets
- 关于ARM9协处理器CP15及MCR和MRC指令
- linux 命令 wget
- 12种常见的设计模式
- dojo小例子(34)带Ajax异步验证功能的ValidationTextBox
- SwipeRefreshLayout.setRefreshing(true)不起作用解决办法
- C++基础---有返回值类型函数(返回非引用类型)
- HTTP 错误 404.15 - Not Found 请求筛选模块被配置为拒绝包含的查询字符串过长的请求。
- http的请求方法
- 使用目前hadoop内置的序列化类(不使用自定义序列化类),实现流量统计的功能