刪除vector重複元素


突然找不到這個,還查了一下書。
C++ Primer 3/e p.1193

然後自己keyin了一個簡單的程式
成功。

執行結果:

開始了
0, 1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 6, 7, 7, 7, 8, 8, 9,
0, 1, 2, 4, 5, 6, 7, 8, 9, 4, 5, 5, 5, 6, 7, 7, 7, 8, 8, 9,
0, 1, 2, 4, 5, 6, 7, 8, 9,
結束了
Press any key to continue


程式碼:

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

void show(std::vector<int>& vch)
{
    for (std::vector<int>::iterator it = vch.begin(); it != vch.end(); ++it)
        std::cout << *it << ", ";
    std::cout << std::endl;
}

int main()
{
    std::cout << "開始了" << std::endl;
    std::vector<int> vch;
    std::vector<int>::iterator eraseit;
 

    for (int i = 0; i<20; ++i)
    {
        //std::cout << i << std::endl;
        vch.push_back(rand()%10);
    }
    std::sort(vch.begin(), vch.end());  //排序
    show(vch);
    eraseit = std::unique(vch.begin(), vch.end());  //排不重覆元素
    show(vch);
    vch.erase(eraseit, vch.end()); //沒被排到的刪掉
    show(vch);

    std::cout << "結束了" << std::endl;
    return 0;
}

沒有留言:

張貼留言

(什麼是留言欄訊息?)