views:

537

answers:

2

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!

+5  A: 

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.

Alex Martelli
Rafael Almeida
@Rafael: This sample compiles just fine for me too. Maybe you could post a more complete segment of your code that actually reproduces the specific error?
goldPseudo
Yes @Rafael, like @goldPseudo says -- your exact command line on this exact snippet I gave (copied and pasted into a file) compiles happily (with several g++ versions, too). Please do so copy and paste it and try to confirm you don't have a broken g++;-), then edit your answer to show a minimal complete failing case please!
Alex Martelli
+1  A: 

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.

goldPseudo
Hello! Please read the comment to Alex's answer!
Rafael Almeida