c++ - Large POD as tuple for sorting -
i have pod 30 members of various types , wanting store thousands of pods in container, , sort container 1 of members.
for example:
struct person{ int idnumber; ....many other members }
thousands of person
objects want sort idnumber
or other member choose sort by.
i've been researching while today , seems efficient, or @ least, simplest, solution not use struct
@ all, , rather use tuple
can pass index number custom comparison functor use in std::sort
. (an example on this page shows 1 way implement type of sort easily, on single member of struct
make templating not easy since must refer member name, rather index tuple
provides.)
my two-part question on approach 1) acceptable tuple large, dozens of members? , 2) there equally elegant solution continuing use struct
instead of tuple
this?
you can make comparator stores pointer member internaly knows member take comparison:
struct pod { int i; char c; float f; long l; double d; short s; }; template<typename c, typename t> struct comp { explicit comp(t c::* p) : ptr(p) {} bool operator()(const pod& p1, const pod& p2) const { return p1.*ptr < p2.*ptr; } private: t c::* ptr; }; // helper function make comparator template<typename c, typename t> comp<c,t> make_comp( t c::* p) { return comp<c,t>(p); } int main() { std::vector<pod> v; std::sort(v.begin(), v.end(), make_comp(&pod::i)); std::sort(v.begin(), v.end(), make_comp(&pod::d)); // etc... }
to further generalize this, make make_comp
take custom comparator, can have greater-than , other comparisons.
Comments
Post a Comment