std::uniqueするときはsortを忘れないこと
std::uniqueするときはstd::sotrしてからじゃないと正しくならない点に注意せんといかん。unique_copyでも似たようなコード書ける。
#include <iostream> #include <algorithm> #include <vector> int main () { std::vector<int> v; v.push_back(0); v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(0); v.push_back(0); //vの中からユニークに値を抽出 std::sort(v.begin(), v.end()); std::vector<int> x(v.begin(), std::unique(v.begin(), v.end())); std::sort(v.begin(), v.end()); std::vector<int> y; std::unique_copy(v.begin(), v.end(), std::back_inserter(y)); //表示 struct Show{void operator()(double x){std::cout << x << std::endl;}}; std::for_each(x.begin(), x.end(), Show()); std::for_each(y.begin(), y.end(), Show()); return 0; }
実行結果
0 1 2 3 0 1 2 3