首页 > 解决方案 > C++,运算符<在 std::map

问题描述

问题描述

我将 std::map 定义为:

struct Key         // Key of my dicitonary
{
    float index[3];
};

struct Value       // Value of my dictionary
{
    float color[3];
    float operator[](int &a) const { return color[a]; }
};

Key key = {a, b, c};
Value value = {d, e, f};

std::map<Key, Value> dict = new std::map<Key,Value>;

if (dict.count(key) < 1) {      // If key does not exist, add value
        addrDict[key] = value;
}

问题

运行代码时,出现以下错误:

d:\documents\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\stl_function.h:386:20: error: no match for 'operator<' (operand types are 'const Key' and 'const Key')

据我了解,它无法比较Key已排序的地图中的两个对象。出于这个原因,我需要operator<Key结构中实现(即使我不关心键的顺序,但使用无序映射会返回可能与 g++ 相关的编译器错误)。我只需要保持由三个不同数组组成的键分开。关于如何实现这一目标的任何想法?

我做了什么

我用试错法实现了运算符,这种解决方案返回了我所期望的,但它没有存储所有可能的键:

bool operator<(const Key &rhs) const {
    (index[0]*index[1]*index[2]) < (rhs.index[0]* rhs.index[1]* rhs.index[2]);
}; 

另一方面,如果我这样做:

bool operator<(const Key &rhs) const {
    index[0] < rhs.index[0];
}; 

我只存储几个键,而不是所有可能的键组合。

编辑:解决了变量定义的问题

标签: c++dictionaryoperators

解决方案


推荐阅读