泛型算法 - 1【C++ Primer 学习笔记 - 第十一章】

标准容器定义了很少的操作,如添加、删除元素,访问第一个、最后一个元素,获取容器大小等。
但是,用户可能需要其他更多的有用操作,如:排序、查找、查找最大元素、查找最小元素等,
为了应对这种需要,
标准库并没有为每种容器类型都定义实现相应的成员函数,而是定义了一组 泛型算法
因为他们实现共同的操作,因此,称为算法
所谓泛型,指的是,它们可以操作在多种容器类型上,如标准库类型 vector、 list ,内置数组类型、甚至其他类型的序列。

自定义类型,只要与标准库兼容,同样可以使用这些泛型算法。


#include <algorithm>
#include <numeric>


//using std::list;
//using std::find_first_of;
int search_value = 42;
vector<int> ivec;
ivec.push_back(42);
ivec.push_back(10);

vector<int>::const_iterator iter = find(ivec.begin(), ivec.end(), search_value);
cout << "The value " << search_value
	<< (iter == ivec.end() ? " is not present." : " is present.") 
	<< endl;


int ia[6] = {28, 283, 48, 42, 42, 90};	
int *pint = find(ia, ia+6, search_value);
// accumulate:累加求和
// 第三个参数,是累加的初值
// 返回类型,即是第三个实参的类型
// 元素类型必须与第三个实参类型兼容
int isum = accumulate(ia, ia+6, 1);

vector<string> svec;
svec.push_back("a");
svec.push_back("b");

string ssum = accumulate(svec.begin(), svec.end(), string(""));
cout << "The value " << search_value
	<< (pint == ia+6 ? " is not present." : " is present.") 
	<< endl;
cout << "int sum : " << isum << endl;
cout << "string sum : " << ssum << endl;

vector<string> svecUsers;
list<char *> clistAdmins;
svecUsers.push_back("Xiaoming");
svecUsers.push_back("Zhangsan");
sve
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值