c++ - 将 vector 中的每个项目与其他每个项目进行比较,同时删除一些元素?

标签 c++ loops vector polymorphism shared-ptr

我需要编写一个函数来比较 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);
        }
    }
}

但是,当我迭代空(已删除)元素或超出数组末尾或其他元素时,我不断遇到问题。我不断以这种或另一种方式重新配置它,但其中一个问题不断出现。

当您将 vector 的每个元素与其他每个元素进行比较,并且在此过程中有时会删除一些元素时,处理问题的最明智、最干净的方法是什么?

此外,如果我想打印有关找到的每个重叠以及删除的形状的一些信息,该怎么办?

最佳答案

您可以使用erase-remove成语:

auto it = vec.begin();
auto end = vec.end();
while( std::distance( it, end ) > 1 ) {
     auto condition = [shape=*it]( const auto &other ) { return shape->overlaps( other ); };
     end = std::remove_if( ++it, end, condition );
}
vec.erase( end, vec.end() );

此 lambda 语法需要 C++14,但如果需要,可以轻松修改它以与 C++11 一起使用(例如,通过在 lambda 之前引入临时变量 shape ,或捕获 按值而不是引用)。

关于c++ - 将 vector 中的每个项目与其他每个项目进行比较,同时删除一些元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47701298/

相关文章:

c++ - Log4cplus RollingFileAppender 是否异步

c++ - 如何使用类型未知的成员创建一个可以在列表/vector 中使用的类?

vector - 为什么 &[T] 参数也接受 &Vec<T>?

c++ - BLAS Level 2 band matrix-vector product 多个 vector

c++ - STL vector 错误 : Unknown type name

c++ - 电网中最少传输的最佳图算法

c++ - Visual Studio OpenCV 错误 C2664

loops - 8086 Assembly - 更好的数据存储/操作?

.net - 循环访问 DataView 中的行

php - 在wordpress中获取帖子的作者ID