文档详情

C++Primer(第4版)习题解答_第十一章.docx

发布:2017-11-16约1.44万字共18页下载文档
文本预览下载声明
第十一章 泛型算法1.algorithm头文件定义了一个名为count的函数,其功能类似于find。这个函数使用一对迭代器和一个值做参数,返回这个值出现的次数的统计结果。编写程序读取一系列int型数据,并将它们存储到vector对象中然后统计某个指定的值出现了多少次。// 11.17_11.1_int_to_vector_count.cpp : 定义控制台应用程序的入口点。//#include stdafx.h#include vector#include iostream#include algorithmusing namespace std;int _tmain(int argc, _TCHAR* argv[]){cout \tInput some int numbers ( ctrl + z to end):\n\t ;vectorint iVec;int iVal;while ( cin iVal )iVec.push_back( iVal );cout \n\tInput a num to search in the iVec: ;cin.clear();cin iVal; int iCnt = 0;if ( iCnt = count( iVec.begin(), iVec.end(), iVal )){cout \n\tThe value iVal occurs iCnt times. endl;}system(pause);return 0;}2.重复前面的程序,但是,将读入的值存储到一个string类型的list对象中。// 11.17_11.2_list_string_count.cpp : 定义控制台应用程序的入口点。//#include stdafx.h#include string#include list#include iostream#include algorithmusing namespace std;int _tmain(int argc, _TCHAR* argv[]){cout \tInput some strings numbers ( ctrl + z to end):\n\t ;liststring strLst;string str;while ( cin str )strLst.push_back( str );cout \n\tInput a string to search in the strList: ;cin.clear();cin str;size_t iCnt = 0;if ( iCnt = count( strLst.begin(), strLst.end(), str)){cout \n\tThe string str occurs iCnt times. endl;}system(pause);return 0;}3.用accumulate统计vectorint容器对象中的元素之和。// 11.19_11.3_accumulate_vector_int.cpp : 定义控制台应用程序的入口点。//#include stdafx.h#include vector#include iostream#include algorithm#include numericusing namespace std;int _tmain(int argc, _TCHAR* argv[]){cout \tInput some int numbers ( ctrl + z to end):\n\t ;vectorint iVec;int iVal;while ( cin iVal ){iVec.push_back( iVal );}cout \n\tInput a int num for the first num: ;cin.clear();cin iVal;if ( iVal= accumulate( iVec.begin(), iVec.end(), iVal ) ){cout \n\tThe sum of all the members and iVal is: iVal endl;}system(pause);return 0;}4.假定v是vectordouble类型的对象,则调用accumulate( v.begin(), v.end(), 0 )是否有错?如果有的话,错在哪里?没有错,accumulate函数必须满足第三个实参的类型与容器内的意思匹配,或者可以转化为第三个实参的类型。本题中double可以转化为int类型,但是会有较大误差。5.对于本节调用find_first_of
显示全部
相似文档