std ::映射以构造为钥匙
std::map with struct as key
我尝试使用std ::映射键为struct,但在查找键时失败了。这里怎么了?查找找不到,但插入不会改变地图中的计数.....
#pragma once
#include <map>
struct OccTestdef
{
public:
int Typ;
int Length;
OccTestdef(int typ, int length) :Typ(typ), Length(length) {};
bool operator < (const OccTestdef& R) const
{
if (Typ < R.Typ) return true;
if (Length < R.Length) return true;
return false;
}
};
typedef std::map<OccTestdef, int> Testmap;
typedef std::pair<OccTestdef, int> Testpair;
class testocc
{
public:
testocc();
~testocc(){}
bool runtest();
private:
Testmap tests;
int addOrInsert(int left, int num, int value);
};
和CPP:
#include "testocc.h"
testocc::testocc()
{
tests = Testmap();
}
// Will Return the Map-Value if found or -1 if new Inserted
int testocc::addOrInsert(int left, int num, int value)
{
int res;
OccTestdef tn(left, num);
auto result = tests.find(tn);
if (result != tests.end()) {
res = result->second;
}
else
{
tests.insert(Testpair(tn, value));
res = -1;
}
return res;
}
bool testocc::runtest()
{
int res;
bool result;
// Fill map with 4 Entries
tests.insert(Testpair( OccTestdef(1, 100), 1));
tests.insert(Testpair(OccTestdef(1, 200), 2));
tests.insert(Testpair(OccTestdef(1, 300), 3));
tests.insert(Testpair(OccTestdef(1, 400), 4));
result = (tests.size() == 4);
// Try to find or Insert
res = addOrInsert(1, 200, 2);
//res should be 2
result = (res == 2);
result = (tests.size() == 4);
res = addOrInsert(2, 200, 20);
// Res must be -1 because new inserted
result = (res == -1);
// Count is not changed
result = (tests.size() == 5);
//These fails why?
res = addOrInsert(2, 200, 20);
//res should be 20
result = (res == 20);
return result;
}
我不明白为什么test.find((无法正常工作。
您的opeator<
不会正确订购元素,因为如果Typ
较小或Length
较小,则返回true。
#include <tuple>
bool operator < (const OccTestdef& R) const
{
return std::tie(Typ, Length) < std::tie(R.Typ, R.Length);
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在C++中搜索嵌套多映射值
- 错误处理.将系统错误代码映射到泛型
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 递归无序映射
- std ::映射以构造为钥匙