c++ primer之10.2 初识泛型算法

标准库提供了超过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 写容器元素的算法

 

转载于:https://www.cnblogs.com/dongdongTang/p/6670580.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值