例如,下面给出的两个结构,如点和正方形,如果可以这样做,我如何向其中插入新元素?
typedef struct _point{
int x;
int y;
}Point;
typedef struct _square{
float belowLeftX;
float belowLeftY;
}Square;
multimap <Square, Point > dictionary;
是的,作为键的结构与作为键的类没有什么不同。您有两个选项可以让代码正常工作。
选项1:供应方形订单。
typedef struct _square {
float belowLeftX;
float belowLeftY;
bool operator<(struct _square const& rhs) const
{
if (belowLeftX < rhs.belowLeftX) return true;
if (rhs.belowLeftX < belowLeftX) return false;
return belowLeftY < rhs.belowLeftY;
}
选项2:向字典提供正方形类型的排序。
auto comparator = [](Square const& lhs, Square const& rhs)
{
if (lhs.belowLeftX < rhs.belowLeftX) return true;
if (rhs.belowLeftX < lhs.belowLeftX) return false;
return lhs.belowLeftY < rhs.belowLeftY;
};
std::multimap <Square, Point, decltype(comparator)> dictionary(comparator);