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

c++ STL常见算法和迭代器

2016-05-29 20:21 471 查看
STL标准化了容器的使用方法,所以可以使用通用的算法和迭代器来操作容器,这里总结下常用的容器算法和迭代器用法。

1.通用算法

通用算法的参数形式常见如下:

函数[_copy/_if]( 起始迭代器、终止迭代器、[目标迭代器]、[待查找值]、[自定义函数])

一般我们传入一对迭代器,进行计算/排序等操作,经常需要对比元素大小,这时候可以使用默认操作函数,也可以自定义函数来自定义比较操作。

1)._copy后缀代表复制元素到制定迭代器

2)._if后缀代表使用自定义函数来自定义比较操作,很多函数没有_if后缀,是通过函数重载来完成的。

需要引入algorithm库,有时候也需要numeric[accumulate等]、xutility[fill_n等]库。

常见使用方法,如下:

vector<int> v(5,0);
vector<int> v2;

//accumulate
int a = accumulate(v.begin(), v.end(), 10);
cout << a << endl;

a = accumulate(v.begin(), v.end(), 10, accu_func);
cout << a << endl;

//fill/fill_n
fill(v.begin(), v.end(), 10);
fill_n(v.begin(), 2, 20);//一定要保证不要写超过下标
fill_n(back_inserter(v), 5, 30);

//replace/copy/replace_copy 带_copy后缀的会复制创建新的对象
replace(v.begin(), v.end(), 20, 25);
copy(v.begin(), v.begin()+3, back_inserter(v2));
replace_copy(v.begin(), v.begin()+3, back_inserter(v2), 25, 24);//将原有的25替换成24,再插入到目标中

OutputV(v);
OutputV(v2);

//unique/unique_copy
vector<int>::iterator iterEnd = unique(v.begin(), v.end());//Unique会将待删除的元素都移到当前最后,iterEnd指向第一个待删除的元素
OutputV(v);
v.erase(iterEnd, v.end());

unique_copy(v.begin(), v.end(), back_inserter(v2));

OutputV(v);
OutputV(v2);

//sort/stable_sort
sort(v2.begin(), v2.end());
OutputV(v2);

vector<CStringA> s;
s.push_back("23234");
s.push_back("34");
s.push_back("565");
s.push_back("7687878");
s.push_back("767");
stable_sort(s.begin(),s.end(),compare_length);

OutputV(s);

//find/find_if
int iA[] = {1,2,3,4,5,6,7,8,9};
vector<int> aa(iA, iA+9);
OutputV(aa);

vector<int>::iterator iter = find(aa.begin(), aa.end(), 3);
if (iter != aa.end())
{
cout << *iter << endl;
}

//count/count_if _if后缀都是加判断条件的
int nCnt = count_if(aa.begin(), aa.end(), count_compare);
cout << nCnt << endl;


2.常用迭代器

STL除了正常迭代器外,还有三个较为常见的迭代器:

需要引入interator库,

1).插入迭代器

//插入操作符-back_inserter/front_inserter
list<int> l;
fill_n(front_inserter(l), 2, 1);
fill_n(front_inserter(l), 2, 2);
fill_n(back_inserter(l), 2, 3);
OutputV(l);


2).反向迭代器

//反向迭代器-reverse_iterator
deque<int> d;
d.push_back(1);
d.push_back(2);
d.push_back(3);
for (deque<int>::reverse_iterator iter=d.rbegin(); iter!=d.rend(); iter++)
{
cout <<*iter << "--";
}


3).流迭代器

//流迭代器-输入可判断是否相等,输出不能判断,只能自增
vector<int> v;
istream_iterator<int> iter(cin), iterEnd;
copy(iter, iterEnd, back_inserter(v));
OutputV(v);

cin.clear();//清除上一次流状态,否则无法继续输入
istream_iterator<int> iter1(cin), iterEnd1;
ostream_iterator<int> o_iter(cout, "-->>");//输出以-->>分割元素
copy(iter1, iterEnd1, o_iter);


本文完整演示代码下载链接

原创,转载请注明来自http://blog.csdn.net/wenzhou1219
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: