您的位置:首页 > 编程语言 > C语言/C++

C++Primer第五版 10.1节练习

2015-09-18 07:43 477 查看
练习10.1:头文件algorithm中定义了一个名为count的函数,它类似find,接受一对迭代器和一个值作为参数。count返回给定值在序列中出现的次数。编写程序,读取int序列存入vector中,打印有多少个元素的值等于给定值。

答: 见练习10.1.cpp

练习10.2:重做上一题,但读取string序列存入list中。

答:见练习10.2.cpp

练习10.1

/*
*练习10.1 
*2015/8/11 
*问题描述:练习10.1:头文件algorithm中定义了一个名为count的函数,它类似find,接受一对迭代器和一个值作为参数。count返回给定值在序列中出现的次数。编写程序,读取int序列存入vector中,打印有多少个元素的值等于给定值。 
*说明:count的使用
*作者:Nick Feng
*邮箱:nickgreen23@163.com 
*/

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int value = 0;
    int cnt = 0;
    vector<int> vec;

    while(cin >> value)
        vec.push_back(value);
    cnt = count(vec.begin(), vec.end(),10);
    cout << "10 appears " << cnt <<" times" << endl;
    return 0;
}


练习10.2

/*
*练习10.2
*2015/8/11 
*问题描述:练习10.2:重做上一题,但读取string序列存入list中。
*练习10.1:头文件algorithm中定义了一个名为count的函数,它类似find,接受一对迭代器和一个值作为参数。count返回给定值在序列中出现的次数。编写程序,读取int序列存入vector中,打印有多少个元素的值等于给定值。 
*说明:count的使用
*作者:Nick Feng
*邮箱:nickgreen23@163.com 
*/

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int main()
{
    int cnt = 0;
    string word;
    list<string> lst;
    while(cin >> word)
        lst.push_back(word);
    cnt = count(lst.begin(), lst.end(), "good"); 
    cout << "'good' appears " << cnt << " times" << endl;

    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: