标准库提供了超过100个算法,这些算法都有一致的结构和类似的用法。除了少数例外,标准库算法都对一个范围内的元素进行操作。范围分别用第一个元素和尾元素之后位置的迭代器。理解算法的最基本的方法就是了解他们是否读取元素、改变元素或重排元素。
10.2.1 只读算法
有find和accumulate(求和)
1 #include <iostream> 2 #include <numeric> 3 #include <vector> 4 5 using namespace std; 6 7 int main() 8 { 9 vector<int> vec = {1, 9, 10, 5}; 10 int sum = accumulate( vec.begin(), vec.end(), 0 );//对vec中的元素求和,和的初值是0 11 12 cout << "sum:" << sum; 13 return 0; 14 }
Note:accumulate的第三个参数的类型决定了函数中使用哪个加法运算符以及返回值的类型,即:序列中元素类型必须与第三个参数匹配,或者能转换为第三个参数的类型。
另外一个例子:
1 #include <iostream> 2 #include <numeric> 3 #include <vector> 4 #include <list> 5 6 using namespace std; 7 8 int main() 9 { 10 list<string> strList = { "chuan", "dong" }; 11 12 string strSum = accumulate( strList.begin(), strList.end(), string("xu") ); 13 //string strSum = accumulate( strList.begin(), strList.end(), "" );//错误const char*没有定义+ 14 15 16 cout << "strSum:" << strSum; 17 return 0; 18 }
操作两个序列的算法
只读算法equal,用于确定两个序列是否保存相同的值。
1 equal( roster.cbegin(), roster.cend(), roster1.cbegin() );//roster1中的元素数目应该至少与roster一样多
10.2.1节练习
10.3
1 #include <iostream> 2 #include <numeric> 3 #include <vector> 4 5 using namespace std; 6 7 int main() 8 { 9 vector<int> nVec = { 1, 0, 8, 4 }; 10 int nSum = accumulate( nVec.begin(), nVec.end(), 0 ); 11 12 cout << "nSum:" << nSum; 13 return 0; 14 }
10.4
1 #include <iostream> 2 #include <vector> 3 #include <numeric> 4 5 using namespace std; 6 7 int main() 8 { 9 vector<double> v = { 10.1, 20,3 }; 10 double dSum = accumulate( v.begin(), v.end(), 0 ); 11 12 cout << "dSum:" << dSum; 13 return 0; 14 } 15 16 /** 17 * 答:错误,第三个参数0,导致浮点型转换到整型过程中,部分数据丢失,结果不符。 18 * /
10.5
1 #include <iostream> 2 #include <numeric> 3 #include <vector> 4 #include <list> 5 6 using namespace std; 7 8 int main() 9 { 10 list<char*> listRoster = { "xcd" }; 11 list<char*> listRoster1 = { "xcd1" }; 12 13 bool isEqual = equal( listRoster.begin(), listRoster.end(), listRoster1.begin() ); 14 15 cout << "isEqual: " << isEqual; 16 return 0; 17 }
/**
* 没有什么问题
*/
10.2.2 写容器元素的算法