《C++ primer》--第11章

习题11.1 algorithm头文件定义了一个count的函数,其功能类似于find。这个函数使用一对迭代器和一个值做参数,返回这个值出现次数的统计结果。编写程序读取一系列int型数据,并将它们存储到vector对象中,然后统计某个指定的值出现了多少次。

//读取一系列int数据,并将它们存储到vector对象中,
//然后使用algorithm头文件中定义的名为count的函数,
//统计某个指定的值出现了多少次
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std; int main()
{
int ival , searchValue;
vector<int> ivec; //读入int型数据并存储到vector对象中,直至遇到文件结束符
cout<<"Enter some integers(Ctrl+Z to end): "<<endl;
while(cin >> ival)
ivec.push_back(ival); cin.clear(); // 使输入流重新有效 //读入欲统计其出现次数的int值
cout<<"Enter an integer you want to search: "<<endl;
cin>>searchValue; //使用count函数统计该值出现的次数并输出结果
cout<<count(ivec.begin() , ivec.end() , searchValue)
<<" elements in the vector have value "
<<searchValue<<endl; return 0;
}

习题11.3 用accumulate统计vector<int>容器对象中的元素之和。

解答:

 //读取一系列int型数据,并将它们存储到vector对象中,
//然后使用algorithm头文件中定义的名为accumulate的函数,
//统计vector对象中的元素之和
#include<iostream>
#include<vector>
#include<numeric>
using namespace std; int main()
{
int ival;
vector<int> ivec; //读入int型数据并存储到vector对象中,直至遇到文件结束符
cout<<"Enter some integers(Ctrl+z to end): "<<endl;
while(cin >> ival)
ivec.push_back(ival); //使用accumulate函数统计vector对象中的元素之和并输出结果
cout<<"summation of elements in the vector: "
<<accumulate(ivec.begin() , ivec.end() , ) //统计vector对象中的元素之和
<<endl; return ;
}

11.13 解释三种插入迭代器的区别。

解答:

三种插入迭代器的区别在于插入元素的位置不同:

  • back_inserter,使用push_back实现在容器末端插入。
  • front_inserter,使用push_front实现在容器前段插入。
  • inserter,使用insert实现在容器中指定位置插入。

因此,除了所关联的容器外,inserter还带有第二个实参——指向插入起始位置的迭代器。

上一篇:[转]支付宝接口程序、文档及解读(ASP.NET)


下一篇:从循环添加事件谈起对JS闭包的理解