c++ - set of pointers with custom comparator -


struct classcomp ;        typedef struct basic{   int ;   set<base*,classcomp> b ;   int c ; } base ;  classcomp{   bool operator() (const base& *lhs, const base& *rhs) const{     return (*lhs).a < (*rhs).a;} }; 

i want create set of pointers of datatype base comparator function classcomp .where code gone wrong.someone please help

from see in code, you've several places you're trying use dependent declarations don't exist yet. fixing various problems, 1 way is:

struct base; //forward decl announces exist (sooner or later)  struct classcomp {     // uses forward decl before in arguments. since we're     //  using pointers, no other type info required. don't     //  implement yet (we can't, don't know     //  "base" yet).     bool operator ()(const base* lhs, const base* rhs) const; };  // define "base". when set declared provide //  custom comparator type has yet fleshed out, //  that's ok. know *will* (it provides //  proper operator() overload). struct base {     int a;     std::set<base*, classcomp> b ;     int c; };  // know "base" looks like. can use //  implement comparator operator () , finish  //  started before. inline bool classcomp::operator()(const base* lhs, const base* rhs) const {     return lhs->a < rhs->a; } 

from there, can use base as-is or derive , shove shove pointers of either b collection of given base (which wouldn't do, have foisted of using smart pointers, that's issue separate question).


nested comparator

this can considerably simpler if nest comparator within base in first place, , may want consider that. in doing bring need in 1 place:

struct base {     struct cmp_ptr     {         bool operator()(const base* lhs, const base* rhs) const         {             return lhs->a < rhs->a;         }     };      int a;     std::set<base*, cmp_ptr> b ;     int c;     }; 

personally, prefer latter. if need use comparator type somewhere else, can acquired using base::cmp_ptr, clearer (to me @ least) in intent.

hope helps.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -