标签归档:c++ primer

c++ primer 5 exercise 10.9

c++ primer 5 exercise 10.9

实现自己的elimDups程序。测试你的程序,分别在读取输入后、调用unique后以及调用erase后打印vector
程序实现:

// sort and elimDups
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using std::cin;
using std::cout;
using std::ends;
using std::endl;
using std::string;
using std::vector;
using std::sort;
using std::unique;

vector<string> strToVec(const string line, const string separators);
void show(vector<string> const &words);
void elimDups(vector<string> words);
int main(void)
{
        const string Separators = " \t:;,\n\r\f\v";
        string str("the quick red fox jumps the slow red turtle");

        // string turn on vector<sting>
        vector<string> vec;
        vec = strToVec(str, Separators);

        // show vector<string>
        cout << "string to vector<sting>..." << endl;
        show(vec);

        // elimDups()
        cout << "\nelimDups()..." << endl;
        elimDups(vec);

        return 0;
}

vector<string> strToVec(const string line, const string separators)
{
        vector<string> vec;
        string word;
        std::string::size_type startPos = 0, endPos = 0;
        std::string::size_type wordLen = 0;

        while ((startPos = line.find_first_not_of(separators,
                endPos)) != std::string::npos) {
                endPos = line.find_first_of(separators, startPos);
                if (endPos == std::string::npos)
                        wordLen = line.size() - startPos;
                else
                        wordLen = endPos - startPos;
                word.assign(line.begin() + startPos,
                        line.begin() + startPos + wordLen);
                vec.push_back(word);
        }

        return vec;
}

void show(vector<string> const &words)
{
        for (const auto s : words)
                cout << s << " ";
        cout << endl;

        return;
}

void elimDups(vector<string> words)
{
        sort(words.begin(), words.end());
        show(words);

        auto end_unique = unique(words.begin(), words.end());
        show(words);

        words.erase(end_unique, words.end());
        show(words);

        return;
}

程序测试结果:

[lhf@localhost 10-9]$ ./elimDups
string to vector<sting>...
the quick red fox jumps the slow red turtle

elimDups()...
fox jumps quick red red slow the the turtle
fox jumps quick red slow the turtle the red
fox jumps quick red slow the turtle