首页 > 代码库 > C++primer 10.2.1节练习

C++primer 10.2.1节练习

练习10.3

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 #include <stack>
 5 #include <algorithm>
 6 #include <numeric>
 7 #include <list>
 8 
 9 using namespace std;
10 
11 
12 int main()
13 {
14     vector<int> vec{ 1,2,3,4,5,6,7,8,9,10 };
15     int val = 0;
16     auto num = accumulate(vec.cbegin(), vec.cend(), val);
17     cout << num << endl;
18     system("pause");
19     return 0;
20 }

练习10.4

最后返回的值精度会丢失,但编译器不会提示有错误,因为accumulate的第三个参数的类型决定了函数中使用哪个加法运算符一级返回值的类型;

练习10.5

如果写成 char * 会发出警告,表示字符串可以修改,而例子中的字符串不允许修改,更好的方法是写成const char *; 

 1 #include<iostream>
 2 #include<string>
 3 #include <iostream>
 4 #include <string>
 5 #include <vector>
 6 #include <algorithm>
 7 using namespace std;
 8 
 9 int main()
10 {
11     const char *s1 = "good";
12     const char *s2 = "boy";
13     vector<const char *> roster1, roster2;
14     roster1.push_back(s1);
15     roster1.push_back(s2);
16     roster2.push_back(s1);
17     roster2.push_back(s2);
18 
19     bool flag = equal(roster1.cbegin(), roster1.cend(), roster2.cbegin());
20 
21     if (true == flag)
22         cout << "same..." << endl;
23     else
24         cout << "not same..." << endl;
25     system("pause");
26     return 0;
27 }

 

C++primer 10.2.1节练习