【发布时间】:2023-05-12 11:56:01
【问题描述】:
我有一个std::vector 的rectangle。类定义很简单:
class rectangle
{
public:
rectangle();
rectangle(int leftX, int topY, int width, int height);
rectangle(const rectangle &other);
int x() const;
int y() const;
int width() const;
int height() const;
// Returns the bounding rectangle of this rectangle and the given rectangle.
rectangle united(const rectangle &r) const;
rectangle intersected(const rectangle &r) const;
// Returns true if rectangle intersects with given rectagle else false.
bool intersects(const rectangle &r) const;
};
对于每个矩形,我想看看是否与向量中的另一个矩形相交,然后将它们“合并”(找到边界矩形)如果它们相交。
我很想看看是否有办法使用<algorithm> 中的函数在一系列矩形上执行搜索/组合。任何人都可以就可能的解决方案提出建议吗?寻找简洁而无需重新发明*的东西。
[编辑:] 我应该提到我已经实现了 'intersects()' 和 'united'。
我的最终目标是实现一个适用于我的矩形范围的函数,如下所示:
/// For each rectangle in the vector it test if it intersects with another and return the set of united rectangles.
/// \param v A set of rectangles
/// \return A united set of rectangles.
std::vector<rectangle> test_intersect_and_unite(const std::vector<rectangle> &v)
{
std::vector<rectangle> united;
// ...
return united;
}
我可能会处理少于 20 个矩形。
【问题讨论】:
-
我看到表达的愿望,但没有实际问题。甚至是要求。你试过什么吗?比如,检查每一对?它奏效了吗?如果没有,出了什么问题?
-
@Sembei 我不认为这是重复的,因为我已经实现了“相交”和“联合”。我正在寻找 STL 中的一个函数来处理一系列矩形。
-
For each rectangle, I'd like to see if intersects another rectangle in the vector and then 'unite' them (find the bounding rectangle) if they intersect.,不,你不想要那个,你已经有了它,所以你不应该在问题中要求它。 -
再一次,完全不清楚你想做什么;请尽量自己实现。有十几个或更多的决定,我不知道你在解决方案中想要哪个(结果去哪里?这个联合过程是否通勤?破坏性好吗?我们谈论多少元素?如果 A B C 成对相交,做我们得到 1 2 或 3 个输出矩形?),一个简单的解决方案(连同为什么它不是你想要的)回答了其中的一半以上。我知道这对你来说可能很明显,但我们无法读懂你的想法。
标签: c++ stl-algorithm