练习10.1:
头文件algorithm中定义了一个名为count的函数,它类似find,接受一对迭代器和一个值作为参数。count返回给定值的序列中出现的次数。编写程序,读取int序列存入vector中,打印有多少哥元素等于给定值。
解答:
// count algorithm example
#include // std::cout
#include // std::count
#include // std::vector
int main () {
// counting elements in array:
int myints[] = {10,20,30,30,20,10,10,20}; // 8 elements
int mycount = std::count (myints, myints+8, 10);
std::cout << "10 appears " << mycount << " times.\n";
// counting elements in container:
std::vector myvector (myints, myints+8);
mycount = std::count (myvector.begin(), myvector.end(), 20);
std::cout << "20 appears " << mycount << " times.\n";
return 0;
}
练习10.2:
重做上一题,但读取string序列存入list中。
解答:
// count algorithm example
#include // std::cout
#include // std::count
#include // std::vector
#include // std::string
int main () {
// counting elements in array:
std::string myints[] = {"10","20","30","30","20","10","10","20"}; // 8 elements
int mycount = std::count (myints, myints+8, "10");
std::cout << "10 appears " << mycount << " times.\n";
// counting elements in container:
std::vector myvector (myints, myints+8);
mycount = std::count (myvector.begin(), myvector.end(), "20");
std::cout << "20 appears " << mycount << " times.\n";
return 0;
}
练习10.3:
用accumulate求一个vector
解答:
#include // std::cout
#include // std::vector
#include // std::accumulate
int main () {
// counting elements in array:
int myints[] = {10,20,30,30,20,10,10,20}; // 8 elements
// counting elements in container:
std::vector myvector (myints, myints+8);
std::cout << std::accumulate(myvector.cbegin(), myvector.cend(), 0) << std::endl;
return 0;
}
练习10.4:
假定v是一个vector
解答:
accumulate会先将vector
【引用】accumulate的第三个参数的类型决定了函数中使用哪个加法运算符以及返回值的类型。
所以这里需要这样修改一下
accumulate(v.cbegin(), v.cend(), 0.)
accumulate(v.cbegin(), v.cend(), 0.0)
都是可以的。
练习10.5:
在本节对名册(roster)调用equal的例子中,如果两个名册中保存的都是C风格字符串而不是string,会发生什么?
解答:
自认为这样也是没有问题的,写了段代码进行验证,并没有出错。
#include
#include
#include
#include
using namespace std;
int main(){
vector csl1{"hello world", "hello china"};
vector csl2{"hello world", "hello china"};
cout << equal(csl1.cbegin(), csl1.cend(), csl2.cbegin()) << endl;
}