c++ - 比较实现 C++ 映射不完整类型不允许

标签 c++ dictionary ramcloud

我正在尝试实现自定义 C++ 比较函数,以传递给 std::map。 按照 map API 中的说明,我实现了:

 35 typedef std::pair<uint64_t, KeyHash> TabletKey;
 36 
 37 class CmpTabletKey {
 38     public:
 39         bool operator()(const TabletKey& key1, const TabletKey& key2) const {
 40             if (!(key1.first < key2.first)) {
 41                 return false;
 42             }
 43             if (!(key2.first < key1.first)) {
 44                 return false;
 45             }
 46 
 47             return true;
 48         }
 49 };

map 是一个属性的类中,我有:

 55 class ObjectFinder {
 56   public:
 57     class TableConfigFetcher; // forward declaration, see full declaration below
 58     class CmpTabletKey;
        // .. more code here
      private:
 97     std::map<TabletKey, ProtoBuf::Tablets::Tablet, CmpTabletKey> tableMap;
     }

我收到以下错误:

/home/ribeiro.phillipe/ramcloud/src/ObjectFinder.h:97:   instantiated from here
/usr/lib/gcc/x86_64-redhatlinux/4.4.6/../../../../include/c++/4.4.6/bits/stl_tree.h:453: 
error: incomplete type ‘RAMCloud::ObjectFinder::CmpTabletKey’ not allowed
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/map:60,

我不知道为什么会这样。此外,我愿意使用 std::less 实现 less

最佳答案

您要在类中声明第二个 CmpTabletKey 对象查找器;实例化 map 时,您在 类,所以这是编译器找到的那个。只需放下 class CmpTabletKey; 类内的语句(或更改它 到 ::CmpTabletKey 的 typedef,或移动整个定义 CmpTabletKeyObjectFinder 类中。

另外,你的比较功能看起来有点奇怪。它看起来 对我来说,如果键相等,它只能返回 true, 它没有定义排序关系。如果你只是想 比较第一个字段:

bool operator()( TabletKey const& lhs, TabletKey const& rhs ) const
{
    return lhs.first < rhs.first;
}

应该可以解决问题。

关于c++ - 比较实现 C++ 映射不完整类型不允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17943409/

相关文章:

c++ - C++11 中的 constexpr if-then-else

c++ - 为什么将 X 而不是 X<T> 用于模板化构造函数和析构函数?

c++ - 如何自定义ostream C++

python-3.x - 合并字典中的两个列表,保留具有多个值的键的重复值

python - 如何将字典转换为键列表,并由值给出重复计数?

python - 为什么使用 `enumerate()` 遍历字典值元组会引发错误?

c++ - 这个指针和所有参数在调用后都是空的(但之前没问题)

c++ - 这个 GetDefaultAudioEndpoint 程序有什么问题?