带有擦除元素的 C++ 嵌套 for 循环 [英] C++ nested for loop with erasing elements

查看:62
本文介绍了带有擦除元素的 C++ 嵌套 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想相互检查一个向量的所有元素.通过检查条件,应删除元素.

I would like to check all Elements of an vector against each other. By checking a condition an element should be removed.

一种方法是通过嵌套的 for 循环擦除元素

One approach was to erase the elements by nested for loops

for (int a = 0; a < rs.size(); a++)
{
    Point A = rs[a];

    for (int b = 1; b <= rs.size(); b++)
    {
        Point B = rs2[b];
        float distance = sqrt(pow(B.x - A.x, 2) + pow(B.y - A.y, 2) * 1.0);

        if (distance < 10.0)
        {
            if (distance > 0)
            {
                rs.erase(rs.begin() + b);
            }
        }
    }
}

但这会在运行时影响向量及其大小.

but this would effect the vector and his size in runtime.

第二种方法是在 unordered_set 中收集 b 的索引,但如何删除原始向量中具有对应索引的元素?

A second approach was to collect the index of b in an unordered_set but how can I delete the elements with the correspondig index in the original vector?

unordered_set<int> index;

for (int a = 0; a < rs.size(); a++)
{
    Point A = rs[a];

    for (int b = 0; b < rs.size(); b++)
    {
        Point B = rs2[b];
        float distance = sqrt(pow(B.x - A.x, 2) + pow(B.y - A.y, 2) * 1.0);

        if (distance < 10.0)
        {
            if (distance > 0)
            {
                index.insert(b);
            }
        }
    }
}

正如您所料,这种方法也不起作用:

As you might expect, this approach does not work either:

for (const int& idx : index)
{
    rs.erase(rs.begin() + idx);
}

有什么帮助吗?

推荐答案

为了尽可能健壮,我会选择 std::for_each.在对每个对象执行的函数中,大致:

To be as robust as possible, I would go with std::for_each. In the function performed on each object, roughly:

  • 进行必要的计算
  • 检查是否保留元素的条件
  • 如果您想保留它,请将其添加到新的输出向量中,否则不要

然后在完成后清除原始向量并交换输入和输出向量.将对象移动到(智能!)指针以提高效率(减少复制).

Then clear the original vector when your are done and swap the in and out vector. Move the objects to (smart!)-pointers for improved efficiency (less copying going on).

For_each 与创建新向量相结合,应使其非常强大,以防止使用 std::vector 时可能发生的潜在大小更改和重新分配.

For_each combined with creating a new vector should make this very robust against potential size changes and re-allocations that might occur when using std::vector.

这篇关于带有擦除元素的 C++ 嵌套 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆