您的位置:首页 > 编程语言 > C语言/C++

C++中一些常用的容器的方法小结(附详细代码及详细注释)

2013-12-08 20:37 846 查看
unique函数的功能是:去除相邻的重复元素(只保留一个)。函数参数:unique(first,last,compare);//first为容器的首迭代器,last为容器的末迭代器,compare为比较函数(可略写)。

unique_copy与unique的唯一区别在于:unique_copy会将进行删除相邻重复元素的结果
保存在另外一个结果容器中。函数参数:unique_copy(first,last,result,compare);//first为容器的首迭代器,last为容器的末迭代器,result为保存结果的容器(原容器的内容不变),compare为比较函数(可略写)。

“我们总结一下你的排序选择:
   ● 如果你需要在vector、string、deque或数组上进行完全排序,你可以使用sort或stable_sort。
   ● 如果你有一个vector、string、deque或数组,你只需要排序前n个元素,应该用partial_sort。
   ● 如果你有一个vector、string、deque或数组,你需要鉴别出第n个元素或你需要鉴别出最前的n个元素,而不用知道它们的顺序,nth_element是你应该注意和调用的。
   ● 如果你需要把标准序列容器的元素或数组分隔为满足和不满足某个标准,你大概就要找partition或stable_partition。
   ● 如果你的数据是在list中,你可以直接使用partition和stable_partition,你可以使用list的sort来代替sort和stable_sort。

#include <iterator>
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
list<int> ilst;
vector<int> ivec;
for(int i=0 ; i != 4; ++i)
{
ilst.push_back(i);
ivec.push_back(i);
}
list<int>::iterator it = find(ilst.begin() , ilst.end() , 3);
//插入迭代器的使用,在find函数返回的迭代器所指向的元素
//前将ivec中迭代器ivec.begin() , ivec.end()范围的所指向的元素插入到ilst中去,插入的过程中将2替换为100
//以上就是replace_copy的作用
replace_copy(ivec.begin() , ivec.end() , inserter(ilst , it) , 2 , 100);
for(list<int>::iterator iter = ilst.begin() ; iter != ilst.end() ; ++iter)
{
cout << *iter << "  ";
}
cout << endl;
//插入迭代器必须添加#include <iterator>头文件
//下面演示push_front 与front_inserter 以及inserter三者的区别
list<int> ilst1 , ilst2 , ilst3;
for(list<int>::size_type i = 0 ; i != 4 ; ++i)
{
ilst1.push_front(i);
}
//1.front_inserter必须在容器提供了push_front操作时才可以用,在vector或者其他没有push_front运算的的容器上使用是不合法的
//2.push_front插入元素时每次都在元素头插入,所以ilst1中是3 2 1 0
//3.front_inserter 来插入元素时将ilst1.begin() , ilst1.end()中的元素插入ilst2每次都在头部插入 所以ilst2中是0 1 2 3
//4.inserter插入迭代器在插入时,就是在ilst3.begin()前一下子插入ilst1.begin() , ilst1.end(),并没有像front_inserter每次都在头部插入,ilst3中3 2 1 0
copy(ilst1.begin() , ilst1.end() , front_inserter(ilst2));
copy(ilst1.begin() , ilst1.end() , inserter(ilst3 , ilst3.begin()));
cout << "ilst1的元素值  ";
for(list<int>::iterator iter = ilst1.begin() ; iter != ilst1.end() ; ++iter)
{
cout << *iter << "  ";
}
cout << endl;
cout << "ilst2的元素值  ";
for(list<int>::iterator iter = ilst2.begin() ; iter != ilst2.end() ; ++iter)
{
cout << *iter << "  ";
}
cout << endl;
cout << "ilst3的元素值  ";
for(list<int>::iterator iter = ilst3.begin() ; iter != ilst3.end() ; ++iter)
{
cout << *iter << "  ";
}
cout << endl;

//unique_copy的演示
vector<int> ivec1;
//现在ilst中的元素是 0 1 2 0 1 100 3 3
//将ilst中不重复的元素复制到空的ivec1中去
//unique_copy只能将ilst中相邻的不重复的元素复制到ivec1中,所以在进行unique_copy前要先对ilst进行排序
//因为数据在list中可以直接用list的函数sort来排序
ilst.sort();
//排序过后进行unique_copy变可以得到ivec1中0 1 2 3 100
unique_copy(ilst.begin() , ilst.end() , inserter(ivec1 , ivec1.begin()));
//输出ivec1中的值
cout << "ivec1 中的值为  " ;
for(vector<int>::iterator it = ivec1.begin() ; it != ivec1.end() ; ++it)
{
cout << *it << " ";
}
cout << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: