c++ - 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];
};
我只存储几个键,而不是所有可能的键组合。
编辑:解决了变量定义的问题
解决方案
推荐阅读
- ios - 通过 Firebase 从 Google 登录获取出生日期和性别
- c - 在 Visual Studio 代码中添加 C 外部库
- php - cURL 在本地工作;服务器上的连接被拒绝
- c++ - 如何创建显示存在递归的调用顺序的跟踪
- r - R中的“Thermal Bar”情节?
- javascript - 有没有办法将行号重新引入堆栈跟踪?
- java - 如何从 Spark Web UI 中删除服务器版本(服务器:Jetty(9.2.z-SNAPSHOT))?
- html - 如何在html中的标签中添加更改链接
- python - 归一化所有帧的概率函数最大值
- selenium - 使用 selenium 和 beautifulsoup 的网页抓取代码无法正常工作