C++ 我可以扩展std::map::lower\u bound来搜索非键类型的参数吗?
这是我的情况的一个例子。我有一个C++ 我可以扩展std::map::lower\u bound来搜索非键类型的参数吗?,c++,stl,stdmap,lower-bound,C++,Stl,Stdmap,Lower Bound,这是我的情况的一个例子。我有一个std::map,我想找到第一个对,其中键是等价键类的任何成员 #include <map> struct Category { int foo; int bar; bool operator < (const Category & rhs) const; bool operator > (const Category & rhs) const; }; struct Key {
std::map
,我想找到第一个对
,其中键是等价键类的任何成员
#include <map>
struct Category
{
int foo;
int bar;
bool operator < (const Category & rhs) const;
bool operator > (const Category & rhs) const;
};
struct Key
{
Category category;
float quality;
bool operator < (const Key & rhs) const
{
if (category < rhs.category)
return true;
else if (category > rhs.category)
return false;
else
return quality < rhs.quality;
}
};
struct Value {};
typedef std::map <Key, Value> Container;
Container::iterator find_low_quality
(
Container & container,
const Category & category
)
{
return container.lower_bound (category);
}
Container::iterator find_high_quality
(
Container & container,
const Category & category
)
{
// some checks need to be done, here omitted for brevity
return --container.upper_bound (category);
}
#包括
结构类别
{
int foo;
int-bar;
布尔运算符<(常数类别和rhs)常数;
布尔运算符>(常量类别和rhs)常量;
};
结构键
{
类别;
浮子质量;
布尔运算符<(常数键和右键)常数
{
if(类别<右侧类别)
返回true;
否则如果(类别>右侧类别)
返回false;
其他的
退货质量
这不起作用,因为map::lower\u bound
和map::upper\u bound
只接受key\u type
(即key
)参数。我无法编译std::lower_bound
,我看到它需要一个LegacyForwardIterator
,但是我很难解释这个规范
就我的地图的
键
的顺序而言,键
与类别
具有兼容的顺序,即:kC++14引入了透明比较器的概念,其中可以使用查找
,下限
,上限
。。。只要比较器显式选择此行为,就可以使用任何可以与键类型进行比较的对象
在您的情况下,您需要添加一个自定义比较器
struct KeyComparator {
// opt into being transparent comparator
using is_transparent = void;
bool operator()(Key const& lhs, Key const& rhs) const {
return lhs < rhs;
}
bool operator()(Key const& lhs, Category const& rhs) const {
return lhs.category < rhs;
}
bool operator()(Category const& lhs, Key const& rhs) const {
return lhs < rhs.category;
}
};
C++14引入了透明比较器的概念,可以使用查找
,下限
,上限
。。。只要比较器显式选择此行为,就可以使用任何可以与键类型进行比较的对象
在您的情况下,您需要添加一个自定义比较器
struct KeyComparator {
// opt into being transparent comparator
using is_transparent = void;
bool operator()(Key const& lhs, Key const& rhs) const {
return lhs < rhs;
}
bool operator()(Key const& lhs, Category const& rhs) const {
return lhs.category < rhs;
}
bool operator()(Category const& lhs, Key const& rhs) const {
return lhs < rhs.category;
}
};