使用带有比较器的map作为std::map参数



假设我使用自定义比较器(如(定义映射

struct Obj
{
int id;
std::string data;
std::vector<std::string> moreData;
};
struct Comparator
{
using is_transparent = std::true_type;
bool operator()(Obj const& obj1, Obj const& obj2) { return obj1.id < obj2.id; };
}
std::map<Obj,int,Comparator> compMap;

有没有一种好的方法可以确保下游用户不必实现比较器来将地图用作地图?

例如,如果我试图将其传递给具有类似类型的函数,编译器会抛出一个错误。

template<class T>
inline void add(std::map<T, int>& theMap, T const & keyObj)
{
auto IT = theMap.find(keyObj);
if (IT != theMap.end())
IT->second++;
else
theMap[keyObj] = 1;
}
add(compMap,newObj); //type error here

编辑:我有点过分强调了这一点,以形成一个通用的案例。然后忽略了明显的

template<class T, class Comp, class Alloc>
inline void add(std::map<T, int, Comp, Alloc>& theMap, T const & keyObj)

仍然存在一次使用无法推断T的问题,但从80个错误增加到1个,因此…进展谢谢大家。

您可以对专用类型进行typedef,并使用该类型代替

std::map<...
typedef std::map<Obj,int,Comparator> compMap_t;
inline void add(compMap_t& theMap, Obj const & keyObj)
...

下游用户要么使用声明的类型

using my_important_map = std::map<Obj,int,Comparator>;

或者更好地使用采用通用地图类型的功能

auto some_function(auto const& map_)
{
//do something with the map and don't care about the ordering
return map_.find(Obj(1));
}

最新更新