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

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

我有 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