Skip to content

Instantly share code, notes, and snippets.

@slwu89
Created July 13, 2018 23:27
Show Gist options
  • Save slwu89/5dcc648b48392d6da53cc6d1fe003009 to your computer and use it in GitHub Desktop.
Save slwu89/5dcc648b48392d6da53cc6d1fe003009 to your computer and use it in GitHub Desktop.
how to sort a vector of pointers to template class
/*
* still need to figure out how to more the lambda function into the class as a friend or something,
* it will be annoying to write lambdas all over the code...
*/
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
template <typename T>
class test {
public:
test(const T time_):time(time_){};
~test(){};
T time;
};
int main(){
std::cout << "starting tests ... \n";
std::vector<std::unique_ptr<test<int> > > vector;
vector.emplace_back(std::make_unique<test<int> >(12));
vector.emplace_back(std::make_unique<test<int> >(1));
vector.emplace_back(std::make_unique<test<int> >(5));
vector.emplace_back(std::make_unique<test<int> >(20));
vector.emplace_back(std::make_unique<test<int> >(8));
vector.emplace_back(std::make_unique<test<int> >(6));
vector.emplace_back(std::make_unique<test<int> >(15));
vector.emplace_back(std::make_unique<test<int> >(10));
std::cout << "prior to sorting ... " << std::endl;
for(auto& it : vector){
std::cout << "time: " << it->time << " " << std::endl;
};
std::sort(vector.begin(),vector.end(),[](const std::unique_ptr<test<int> >& c1, const std::unique_ptr<test<int> >& c2){
return c1->time > c2->time;
});
std::cout << "after sorting ... " << std::endl;
for(auto& it : vector){
std::cout << "time: " << it->time << " " << std::endl;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment