Skip to content

Instantly share code, notes, and snippets.

@muaddib1971
Last active January 21, 2017 05:02
Show Gist options
  • Select an option

  • Save muaddib1971/b34f9d18348edcb303b23d6339c524cc to your computer and use it in GitHub Desktop.

Select an option

Save muaddib1971/b34f9d18348edcb303b23d6339c524cc to your computer and use it in GitHub Desktop.
An example of a class that enforces sorting on a vector.
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iostream>
template<typename T>
struct comparator
{
bool operator()(const T & a, const T & b)
{
return a < b;
}
};
template <typename T>
class sorted_vector : public std::vector<T>
{
private:
static const int default_size=16;
comparator<T> cmp;
public:
sorted_vector(comparator<T> & mycmp, int size=default_size)
: std::vector<T>(size), cmp(mycmp)
{
}
void push_back(const T& t)
{
std::vector<T>::push_back(t);
std::sort(this->begin(), this->end(), cmp);
}
};
int main(void)
{
comparator<int> int_compare;
sorted_vector<int> ints(int_compare);
ints.push_back(3);
ints.push_back(1);
ints.push_back(5);
for(int i:ints)
{
std::cout << i << std::endl;
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment