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

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

10.6节特定容器算法 习题答案

练习10.42:使用list代替vector重新实现10.2.3节(第343页)中的去除重复单词的程序。

【出题思路】

练习链表的特殊操作。

【解答】

本题要使用链表专用的sort和unique算法,与泛型算法的不同点有如下两点:

1.它们是以链表类的成员函数形式实现的,因此使用方式是在链表对象上调用它们,也并不需要迭代器参数指出处理的序列。

2.由于是以成员函数形式实现的,是直接操作容器而非通过迭代器访问容器元素,因此这些算法具有修改容器的能力(添加、删除元素)。例如,unique会调用erase直接真正删除重复元素,容器的大小会变小,而不是像泛型unique算法那样只是覆盖重复元素,并不改变容器大小。因此程序已不再需要调用erase了。

建议读者好好体会泛型算法和专用算法之间的差异,包括上述使用方式上的差异,以及从库的开发者的角度思考两种方式的差异。

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

using namespace std;

inline void output_words(list<string> &words)
{
    for(auto iter = words.begin(); iter != words.end(); iter++)
        cout << *iter << " ";
    cout << endl;
}


void elimDups(list<string> &words)
{
    output_words(words);
    words.sort();
    output_words(words);
    
    words.unique();
    output_words(words);
}


int main(int argc, const char *argv[])
{
    ifstream in(argv[1]);
    if(!in)
    {
        cout << "打开输入文件失败!" << endl;
        exit(1);
    }
    
    list<string> words;
    string word;
    while(in >> word)
        words.push_back(word);
    
    elimDups(words);
       
    return 0;
}

data10_42.txt文件内容为:

the quick red fox jumps over the the slow over red turtle

设置命令行参数

运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值