可以以结构为键来实现多图吗?如果是那么如何?
Can multimaps be implemented with structures as key? If yes then how?
例如下面给出的两个结构,如点和方,如果可以的话,我该如何向其中插入新元素?
typedef struct _point{
int x;
int y;
}Point;
typedef struct _square{
float belowLeftX;
float belowLeftY;
}Square;
multimap <Square, Point > dictionary;
是的,作为键的结构与作为键的 class 没有什么不同。您有两个选项可以让您的代码正常工作。
选项 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:
向字典提供 Square 类型的排序。
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);
例如下面给出的两个结构,如点和方,如果可以的话,我该如何向其中插入新元素?
typedef struct _point{
int x;
int y;
}Point;
typedef struct _square{
float belowLeftX;
float belowLeftY;
}Square;
multimap <Square, Point > dictionary;
是的,作为键的结构与作为键的 class 没有什么不同。您有两个选项可以让您的代码正常工作。
选项 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: 向字典提供 Square 类型的排序。
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);