且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

《C++ primer》--第11章

更新时间:2022-08-16 09:34:41

习题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>容器对象中的元素之和。

解答:

 1 //读取一系列int型数据,并将它们存储到vector对象中,
 2 //然后使用algorithm头文件中定义的名为accumulate的函数,
 3 //统计vector对象中的元素之和
 4 #include<iostream>
 5 #include<vector>
 6 #include<numeric>
 7 using namespace std;
 8 
 9 int main()
10 {
11     int ival;
12     vector<int> ivec;
13 
14     //读入int型数据并存储到vector对象中,直至遇到文件结束符
15     cout<<"Enter some integers(Ctrl+z to end): "<<endl;
16     while(cin >> ival)
17         ivec.push_back(ival);
18 
19     //使用accumulate函数统计vector对象中的元素之和并输出结果
20     cout<<"summation of elements in the vector: "
21         <<accumulate(ivec.begin() , ivec.end() , 0)  //统计vector对象中的元素之和
22         <<endl;
23 
24     return 0;
25 }

 

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

解答:

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

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

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

《C++ primer》--第11章
微信公众号: 猿人谷
如果您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】
如果您希望与我交流互动,欢迎关注微信公众号
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。