如何在C++的循环中从矢量中删除元素

How to remove elements from vector in the cycle in C++

本文关键字:删除 元素 循环 C++      更新时间:2023-10-16

我有 2 个双精度向量:tP 。它们的大小是 m .

我想检查条件:矢量t |t[i]-t[i+1]| < dT,矢量P |P[i]-P[i+1]| < dP

然后,如果条件正确,我应该删除t[i+1]元素(或P[i+1]元素(。

我的代码:

//fill vectors
for (unsigned int i = 0; i < t.size() - 1; i++)
    if (abs(t[i] - t[i + 1]) < dT)
        t.erase(t.begin() + (i + 1));

for (unsigned int j = 0; j < p.size() - 1; j++)
    if (abs(p[j] - p[j + 1]) < dP)
        p.erase(p.begin() + (j + 1));

当我使用erase按索引删除时,这是正确的方法吗?

对于此类任务,最好使用带有谓词的标准算法std::unique,然后将成员函数erase应用于返回的迭代器。

至于你的代码,那么它是无效的。擦除元素时不应增加索引。

这是一个演示程序,展示了如何使用算法std::unqiue

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
int main() 
{
    std::vector<double> v = { 1, 1.5, 3, 4.5, 5 };
    const double delta = 1.0;
    for ( const auto &x : v ) std::cout << x << ' ';
    std::cout << std::endl;
    v.erase( 
        std::unique( v.begin(), v.end(), 
                     [&]( const auto &x, const auto &y ) 
                     { 
                        return ::abs( x - y ) < delta; 
                     } ),
        v.end() );

    for ( const auto &x : v ) std::cout << x << ' ';
    std::cout << std::endl;
    return 0;
}

它的输出是

1 1.5 3 4.5 5 
1 3 4.5