C++primer Plus10.2.3排列容器中的元素並且刪除重複值的算法

C++primer Plus10.2.3排列容器中的元素並且刪除重複值的算法

這裏用到sort和unique算法,因爲算法不能執行容器的操作(刪除重複元素),所以還需要使用vector的erase成員函數
調用所需的頭文件

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

具體操作封裝在elimDups函數中,其中auto end_unique=unique(x.begin(),x.end());`返回一個指向不重複元素末尾的迭代器。

void elimDups(vector<string> &x)
{
    sort(x.begin(),x.end())
    auto end_unique=unique(x.begin(),x.end());
    x.erase(end_unique,x.end());
}

主函數:

using namespace std;
void elimDups(vector<string> &x);
int main() {
    vector<string> words;
    words.push_back("the");
    words.push_back("quick");
    words.push_back("red");
    words.push_back("fox");
    words.push_back("jumps");
    words.push_back("over");
    words.push_back("the");
    words.push_back("slow");
    words.push_back("red");
    words.push_back("turtle");
    elimDups(words);
    for(vector<string>::iterator iter = words.begin(); iter != words.end();++iter)
    {
        cout<<*iter<<" ";
    }
    cout<<endl;
}

函數輸出:

fox jumps over quick red slow the turtle 

Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章