Tutorial :Container of pointers



Question:

I'm having some trouble in declaring a STL Set of pointers to class instances. More specifically, I have this scenario:

class SimulatedDiskFile {    private:      // ...    public:      // ...      struct comparator {        bool operator () (SimulatedDiskFile* const& file_1, SimulatedDiskFile* const& file_2) {          return ((*file_1)->getFileName() < (*file_2)->getFileName());        }      };  }    typedef set<SimulatedDiskFile*, SimulatedDiskFile::comparator> FileSet;  

The code above is not working. Compiler says it didn't find a member SimulatedDiskFile::comparator() function. If I put the function with this declaration (outside the struct), compiler says it was expecting a type.

Now here com my doubts (not only one, but related, I guess):

  • What is the the correct declaration for a set of pointers?
  • What is the correct declaration for a comparison funcion that compares pointers?

I did look up in many places before posting, but I found the references confusing and not quite related to my special case (as stupidly trivial as I think it is - actually, maybe this is the cause). So, any good links are of great help too!

Thanks in advance!


Solution:1

Fixing a few glitches,

#include <set>    class SimulatedDiskFile {    public:      int getFileName() { return 23; }        struct comparator {        bool operator () (SimulatedDiskFile* file_1, SimulatedDiskFile* file_2) {          return (file_1->getFileName() < file_2->getFileName());        }      };  };    typedef std::set<SimulatedDiskFile*, SimulatedDiskFile::comparator> FileSet;  

compiles just fine.


Solution:2

Since you aren't showing where the 'getFileName()' method is supposed to be, I'm just going to go out on a limb and assume that you don't mean to double-dereference your pointers in the comparator. ie, you should do either:

return (file_1->getFileName() < file_2->getFileName());  

or:

return ((*file_1).getFileName() < (*file_2).getFileName());  

but not both.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »