指针容器 [英] Container of pointers

查看:103
本文介绍了指针容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在声明指向类实例的STL指针集时遇到了一些麻烦.更具体地说,我有这种情况:

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;

上面的代码不起作用.编译器说它找不到成员SimulatedDiskFile :: comparator()函数.如果我将函数带有此声明(在struct之外),则编译器会说它在期待类型.

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):

  • 一组指针的正确声明是什么?
  • 比较指针的比较函数的正确声明是什么?

在发布之前,我确实在很多地方进行过查询,但是我发现这些引用令人困惑,并且与我的特殊情况无关(我认为这很琐碎-实际上,也许是原因).因此,任何良好的链接也有很大的帮助!

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!

提前谢谢!

推荐答案

修复了一些小故障,

#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;

编译很好.

这篇关于指针容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆