【发布时间】:2018-08-01 13:43:42
【问题描述】:
所以我有以下 STL std::map 容器
#include <map>
#include <vector>
// ...
class Type
{
std::string key;
int support;
};
std::map<Type, std::vector<int> > index;
我想重载地图,这样下面的两个 if 子句都可以工作:
int main()
{
std::map<Type, std::vector<int> > index;
Type type1;
type1.key = "test";
type1.support = 10;
index[type1] = std::vector<int>();
if (index.find(type1) != index.end())
{
index[type1].push_back(0);
}
// I can not make this work
if (index.find("test") != index.end())
{
index["test"].push_back(0);
}
return 0;
}
我已经尝试过这些重载:
class Type
{
public:
std::string key;
int support;
size_t operator()() const
{
return std::hash<std::string>{}(name);
}
bool operator==(const struct Type& obj) const
{
return (key == obj.key);
}
bool operator<(const struct Type& obj) const
{
return key < obj.key;
}
bool operator<(const std::string& other_key) const
{
return key < other_key;
}
bool operator==(const std::string& other_key) const
{
return other_key == key;
}
};
namespace std
{
template<>
struct hash<Type>
{
size_t operator()(const Type& obj) const
{
return obj();
}
// Specialization here does not seem to work
size_t operator()(const std::string& name) const
{
return std::hash<std::string>{}(name);
}
};
template<>
struct less<Type>
{
bool operator() (const std::string& lname, const std::string& rname)
{
return lname < rname;
}
};
由于在我的模型中,std::string key 字段唯一地定义了类型,我如何重载 std::map 容器以便可以索引容器的项目?我可以在 C++ 中做到这一点吗?
PS:我知道有些代码在重载中可能是多余的
【问题讨论】:
-
您可以为
std::map::find()执行此操作,但您不能为std::map::operator[]执行此操作,因此您可以创建临时Type或仅使用find -
听起来你只需要提供
Type采用任何一种类型的构造函数。那么挑战可能是使它们具有适当的可比性。 -
@FrançoisAndrieux 这对于
std::map::find()自 c++14 以来不是必需的 -
@Slava 我不确定您的评论中的 "that" 指的是什么。
-
@FrançoisAndrieux by "that" 我的意思是您不必创建
Type的实例即可将其传递给find