Container of pointers

痞子三分冷 提交于 2019-12-11 00:29:56

问题


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!


回答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.




回答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.



来源:https://stackoverflow.com/questions/999371/container-of-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!