更新时间:2022-06-11 12:46:14
习题11.1 algorithm头文件定义了一个count的函数,其功能类似于find。这个函数使用一对迭代器和一个值做参数,返回这个值出现次数的统计结果。编写程序读取一系列int型数据,并将它们存储到vector对象中,然后统计某个指定的值出现了多少次。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
//读取一系列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 解释三种插入迭代器的区别。
解答:
三种插入迭代器的区别在于插入元素的位置不同:
因此,除了所关联的容器外,inserter还带有第二个实参——指向插入起始位置的迭代器。
本文转自夏雪冬日博客园博客,原文链接:http://www.cnblogs.com/heyonggang/p/3240865.html,如需转载请自行联系原作者