《C++ Primer》第10章 10.1节习题答案

本篇博客介绍了C++ Primer第10章的内容,主要探讨了标准库中的泛型算法,包括只读和写操作的算法、使用lambda和bind定制操作、插入器、IO流迭代器和反向迭代器的运用。通过练习加深了对泛型思想的理解,展示了如何通过迭代器实现算法与数据结构的解耦,实现对不同类型数据结构的通用操作。
摘要由CSDN通过智能技术生成

《C++ Primer》第10章 泛型算法

导读本章介绍了标准库算法,包括:

●基础的只读算法、写容器元素的算法。

●利用lambda、bind等技术手段定制操作。

●更深入的迭代器知识,如插入器、IO流迭代器、反向迭代器。

●泛型算法对迭代器的分类和算法命名规范,以及特定容器算法。

本章练习的最重要目的是让读者深入理解“泛型”思想,体会标准库是如何通过算法和数据结构的分离来实现泛型的,以及如何通过迭代器在分离的算法和数据结构间架起桥梁,达到算法“不知”数据结构,但又能操纵数据元素的效果。具体内容包括基础算法使用的练习、lambda和定制操作的练习、插入器/IO流迭代器/反向迭代器的练习等。

10.1节 概述 习题答案

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

【出题思路】

本题练习泛型算法的简单使用。

【解答】

泛型算法的使用其实很简单,记住关键一点:泛型算法不会直接调用容器的操作,而是通过迭代器来访问、修改、移动元素。对于本题,将vector的begin和end传递给count,并将要查找的值作为第三个参数传递给它即可。

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

using namespace std;

int main(int argc, const char *argv[]) {

    ifstream in(argv[1]);
    if(!in)
    {
        cout << "打开输入文件失败!" << endl;
        exit(1);
    }

    vector<int> vi;
    int val;

    while(in >> val)
    {
        vi.push_back(val);
    }

    cout << "请输入要搜索的整数:" << endl;
    cin >> val;

    cout << "序列中包含 " << count(vi.begin(), vi.end(), val) << " 个" << val << endl;

    return 0;
}

data10_01.txt里的数据为:

25 36 98 74 24 588 25 694 24 258 636 5 25 478 24 58 24 15 47 24

设置命令行参数

运行结果:

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

【出题思路】

理解“泛型”的优点。

【解答】

可以看到,与上一题对比,程序的变化只在不同类型变量的声明上,而算法的使用部分几乎没有任何差异。

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <list>
#include <string>

using namespace std;


int main(int argc, const char *argv[])
{

    ifstream in(argv[1]);
    if(!in)
    {
        cout << "打开输入文件失败!" << endl;
        exit(1);
    }

    list<string> ls;
    string word;

    while(in >> word)
    {
        ls.push_back(word);
    }

    cout << "请输入要搜索的字符串:" << endl;
    cin >> word;

    cout << "序列中包含 " << count(ls.begin(), ls.end(), word) << " 个 " << word << endl;

    return 0;
}

data10_02.txt里的数据为:

While deleting the derived data eventually worked for me, it didn't help until I rebooted the iPad and OS/X, emptied the trash after using the Finder to delete the derived data, and removed a BLE peripheral connected via a USB port. I don't know which of the steps was required--XCode later compiled with the BLE peripheral attached--but once all of those steps were added to deleting the derived data, the project compiled fine.

设置命令行参数,运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值