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