【发布时间】:2017-12-07 18:12:42
【问题描述】:
我需要编写一个函数,将std::vector<std::shared_ptr<Shape >> shapes_ 的每个元素与每个其他元素进行比较,以确定形状是否重叠,然后删除其中一个重叠的形状。这是我目前所拥有的:
class Shape {
public:
...
virtual bool overlaps(const std::shared_ptr<Shape>&) const = 0;
...
};
class Square : public Shape { ... } ;
class Circle : public Shape { ... } ;
并利用这些类:
std::vector<shared_ptr<Shape>> shapes_;
// ... some code populates the array
for (auto& shape : shapes_) {
// Compare to every other shape
for (unsigned long j = 0; j < shapes_.size(); j++) {
// If they overlap and they aren't the same shape
if (shape->overlaps(shapes_.at(j)) && shape!=shapes_.at(j)) {
shapes_.erase(shapes_.begin() + j);
}
}
}
但是,在迭代空(已删除)元素或超出数组末尾或其他内容时,我一直遇到问题。我一直以这种或其他方式重新配置它,但这些问题之一不断出现。
当您将向量的每个元素与其他所有元素进行比较,并且在此过程中有时会删除一些元素时,什么会被认为是处理问题的最明智、最干净的方法?
另外,如果我想打印一些关于找到的每个重叠的信息,以及被移除的形状怎么办?
【问题讨论】:
标签: c++ loops vector polymorphism shared-ptr