STL C++ Primer算法总结(一)

/ /STL C++ Primer 算法总结(一)
#include<iostream>
#include<vector>
#include<algorithm>//count()
#include<list>
#include<string>
#include<numeric>//accumulate()
#include<iterator>

using namespace std;

bool divide(const string &a)
{
return a.size() > 2;
}

int main()
{
vector<int> a = { 1,2,3,4,5,6,7,8,9,10 };
//find(begin,end,value)//返回第一个value的迭代器,没有返回end
auto result = find(a.begin(), a.end(), 3);
result != a.end() ? cout << "I have found" : cout << "Not found";
//count(begin,end,value)//返回value出现的次数
cout << count(a.begin(), a.end(), 3) << endl;
//accumulate(begin,end,init-value)//返回[begin,end)value和init-value的和
cout << accumulate(a.begin(), a.end(), 5) << endl;//60
//fill(begin,end,value)//将[begin,end)元素重置或填充为value
fill(a.begin(), a.end(), 0);
//fill_n(dest,n,value)向[dest,dest+n)填充或重置为value
fill_n(a.begin(), 3, 5);
//copy(begin_1,end_1,begin_2);将[begin_1,end_1)里的value向[begin_2,end_1-begin_1-1)拷贝
int b[10];
copy(a.begin(), a.end(), b);
for (auto &v : b)
cout << v << ends;
cout << endl;
//replace(begin,end,oldvalue,newvalue)将[begin,end]里oldvalue替换为newvalue
replace(a.begin(), a.end(), 0, 5);
for (auto &v : a)
cout << v << ends;
cout << endl;
/*replace_copy(begin,end,dummy,oldvalue,newvalue)与replace不同的是此算法不会
改变[begin,end)里的值,而是在副本dummy里改动*/
vector<int> dummy;
replace_copy(a.begin(), a.end(), back_inserter(dummy), 5, 0);
for (auto &v : a)
cout << v << ends;
cout << endl;
for (auto &v : dummy)
cout << v << ends;
cout << endl;
/*unique(begin,end)//重排[begin,end)里的value使重复value排在后面并返回
第一个重复value的迭代器
注意: 使用前请确保序列有序主要是使重复value紧邻*/
vector<string> c = { "WH","wh","Marco","marco","wh" };
sort(c.begin(), c.end());
auto frist_repeat = unique(c.begin(), c.end());
c.erase(frist_repeat, c.end());//删除重复value
for (auto &v : c)

cout << v << ends;

/*partition(begin,end,pred)接受一个谓词,以谓词是否为真将容器[begin,end)
划分前半段为真,后半段为假,返回第一个为假的迭代器*/
vector<string> s = { "wh","marco","marco","Marco","R","W" ,"A","B","Boy","boy"};
auto div = partition(s.begin(), s.end(), divide);
for (auto it = s.begin(); it != div; ++it)
cout << *it << ends;
cout << endl;
for (auto it = div; it != s.end(); ++it)
cout << *it << ends;

system("pause");
return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值