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

    解答:

     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还带有第二个实参——指向插入起始位置的迭代器。

  • 相关阅读:
    利用服务器部署Web项目
    JavaWeb解决文件上传后项目需要刷新问题 以及 图片过大 文件上传时间延长
    JavaWeb接入支付宝支付
    JavaWeb实现文件上传功能
    Eclipse Server中没有TomCat
    Eclipse 中没有Dynamic web Project 解决办法
    JavaWeb图形验证码
    elasticsearch常用语句
    关于elasticsearch的安装教程和使用方法
    解决el-table渲染卡顿组件
  • 原文地址:https://www.cnblogs.com/heyonggang/p/3240865.html
Copyright © 2020-2023  润新知