Last active
August 29, 2015 14:03
-
-
Save mitsu-ksgr/8df5a9c4acfbbb6e8a32 to your computer and use it in GitHub Desktop.
【C++】std::vectorをマージして、ソートと重複削除を行うテスト。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**************************************************************************//** | |
* @brief Example of merge std::vector And sort with erase duplicates. | |
* @par Bibliography | |
* http://stackoverflow.com/questions/1041620/most-efficient-way-to-erase-duplicates-and-sort-a-c-vector | |
* | |
* @author Mitsu | |
* @date 2014-07-07. 七夕! | |
******************************************************************************/ | |
#include <chrono> | |
#include <iostream> | |
#include <set> | |
#include <string> | |
#include <sstream> | |
#include <vector> | |
// for test. | |
template <class CONTAINER> | |
std::string dumpContainer(CONTAINER container) | |
{ | |
std::stringstream ss; | |
for(auto v : container) | |
ss << v << ", "; | |
return ss.str(); | |
} | |
// Use for when the number of duplicates is large enough. | |
void sortAndEraseDuplicates_useSet(std::vector<int>& vec) | |
{ | |
// std::set<int> s(vec.begin(), vec.end()); // convert to set. | |
// vec.assign(s.begin(), s.end()); // reconvert to vector. | |
// faster? | |
std::set<int> s; | |
unsigned size = vec.size(); | |
for(unsigned i = 0; i < size; ++i) | |
s.insert(vec[i]); | |
vec.assign(s.begin(), s.end()); | |
} | |
// Use for when the number of duplicates is little. | |
void sortAndEraseDuplicates_useUnique(std::vector<int>& vec) | |
{ | |
std::sort(vec.begin(), vec.end()); // sort for unique. | |
vec.erase(std::unique(vec.begin(), vec.end()), vec.end()); | |
} | |
int main(int argc, char **argv) | |
{ | |
std::vector<int> vec1 = {0, 1, 2, 3, 4}; | |
std::vector<int> vec2 = {3, 4, 2, 3, 5}; | |
std::cout << "vec1: " << dumpContainer(vec1) << std::endl; | |
std::cout << "vec2: " << dumpContainer(vec2) << std::endl; | |
std::cout << "--------------------" << std::endl; | |
//------------------------------ | |
// Merge! | |
vec1.insert(vec1.end(), vec2.begin(), vec2.end()); | |
std::cout << "vec1 insert vec2: " << dumpContainer(vec1) << std::endl; | |
//------------------------------ | |
// Sort & Erase Duplicates! | |
{ // A. Use std::set. | |
std::vector<int> test(vec1.begin(), vec1.end()); | |
sortAndEraseDuplicates_useSet(test); | |
std::cout << "Sort&EraseDuplicates(Use std::set): " << dumpContainer(test) << std::endl; | |
} | |
{ // B. Use std::unique. | |
std::vector<int> test(vec1.begin(), vec1.end()); | |
sortAndEraseDuplicates_useUnique(test); | |
std::cout << "Sort&EraseDuplicates(Use std::unique): " << dumpContainer(test) << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment