C++で任意のデータから重複しない一意データを取得するには、
- データヒストグラムを作成する
- ヒストグラムの各データを一意データとする
だけで良いです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#include <iostream> #include <vector> #include <map> #include <cstdlib> #include <ctime> using namespace std; template<class T> vector<T> GetUniqueData(vector<T> data) { // ヒストグラム map<T, int> hist; // 返却用データ vector<T> ret; // ヒストグラム取得 for(auto itr = data.begin(); itr != data.end(); ++itr) { hist[*itr]++; } // データ詰め替え for(auto itr = hist.begin(); itr != hist.end(); ++itr) { ret.push_back(itr->first); } return ret; } int main() { // 乱数の初期化 srand((unsigned)time(nullptr)); // 入力用データ vector<int> data(10); // 適当なデータの生成 for(auto itr = data.begin(); itr != data.end(); ++itr) { *itr = rand() % 10; // 出力 cout << *itr << endl; } // 一意データ vector<int> unique = GetUniqueData<int>(data); // 出力 cout << "Unique Data" << endl; for(auto itr = unique.begin(); itr != unique.end(); ++itr) { cout << *itr << endl; } return 0; } |
mapの代わりにsetを使っても同じようなことができますが、速度的にはどちらも大して変わらないです。