C++ Primer学习总结 第10章 泛型算法

泛型算法

1、find()泛型只读算法

std::vector<int> v{1,2,3,4,5};
	auto it = find(v.begin(),v.end(),1);
	cout << *it << endl;






2、accumulate()

对所给元素范围求和。第三个参数决定返回类型。

	std::vector<int > v{1,1,1};
	cout << accumulate(v.begin(),v.end(),0);

	std::vector<string> vv{"a","b","c"};
	cout << accumulate(vv.begin(),vv.end(),string(""));





3、equal()

vv大小一定 要>= v的大小。否则返回false。

    std::vector<int> v{1,2,3},vv{1,2,3,4};
	bool res = equal(v.begin(),v.end(),vv.begin());
	cout << res << endl;






4、泛型写容器算法 fill()

注意:写入的数量要<=容器大小。也就是不能越界。

//以下是未定义的
	std::vector<int> v;
	fill_n(v.begin(),10,1);
	cout << v[1];






5、插入迭代器P341,P358。

注意:对插入迭代器it执行*it,++it,–it,it++,it–没有任何作用
只有在容器支持push_back,我们擦可以使用back_inserter,front_inserter同理。
使用back_insertor
    vector<int> v;
	auto it = back_inserter(v);//使用back_inserter();
	*it = 1;
	*it = 2;
	*it = 3;
    for(auto x:v) cout << x <<"\t";cout << endl;//1 2 3

	std::vector<int> vv;
	auto it1 = back_inserter(vv);
	fill_n(it1,3,1);//在空容器上使用fill_n
	for(auto x:vv)cout << x << "\t";//1 1 1
	cout << endl;
使用front_insertor
	deque<int> v;
	auto it = front_inserter(v);//使用back_inserter();
	*it = 1;
	*it = 2;
	*it = 3;
    for(auto x:v) cout << x <<"\t";cout << endl;//3 2 1

使用inserter
	std::vector<int> v{1,2,3};
	auto it = inserter(v,v.begin()+2);
	it = 11;it = 22;it = 33;//始终在v[2]前面插
	for(auto x : v)cout << x <<  "\t";//1 2 11 22 33 3






6、拷贝算法

    vector<int>v1{1,2,3},v2(3);
	auto it = copy(v1.begin(),v1.end(),v2.begin() ); //返回赋值完的尾后元素。
	for(auto x:v2)cout << x << endl;//1 ,2 ,3


	replace(v1.begin(),v1.end(),1,11);
	for(auto x:v1)cout << x << endl;//11 2 3

	std::vector<int> v3;
	replace_copy(v1.begin(),v1.end(),back_inserter(v3),2,22);
	for(auto x:v3)cout << x << endl;//11 22 3



7、排序算法sort和unique

unique并不是真正地删除容器内重复元素,他只不过是把重复元素用不重复元素覆盖,容器后面的空间依然有效,不过是多少就不一定了。
    std::vector<int> v{1,2,3,1,2,3,2,3};
	sort(v.begin(),v.end()); 
	auto it = unique(v.begin(),v.end());
	for(auto x:v)cout << x;
	cout << endl;
	v.erase(it,v.end());
	for(auto x:v)cout << x;	





8、bind函数

using namespace std::placeholders;//必须加上
bool check(string a,int sz){
    return a.size() == sz;
}
int main() 
{
    auto check2 = bind(check,_1,3);
    cout << check2("aaa")<<endl;//1
    cout << check2("aa")<<endl;//0

    auto check3 = bind(check,_2,_1);
    cout << check3(3,"aaa");//1
    cout << check3(3,"aa");//0
    return 0;
}




9、反向迭代器

用base方法将一个反向迭代器 转化为 普通迭代器。

  std::vector<int> v{1,2,3,4};
    auto it = v.rbegin()+1;
    cout << *it;//3

    auto it1 = it.base();
    cout << *it1;//4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值