【问题标题】:How to remove elements from vector in the cycle in C++如何在C ++中的循环中从向量中删除元素
【发布时间】:2018-01-18 19:49:57
【问题描述】:

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

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

如果条件正确,我应该删除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按索引删除时,这是正确的方法吗?

【问题讨论】:

标签: c++ algorithm vector stl erase


【解决方案1】:

对于这样的任务,最好使用带有谓词的标准算法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 

【讨论】:

  • 为什么当我将unique 更改为remove_if 时,lamba 函数出现两个错误?它说关于错误的书面论点?错误 C2780 'auto main::operator ()(const _T1 &,const _T2 &) const':需要 2 个参数 - 提供了 1 个错误 C2672 'operator __surrogate_func':找不到匹配的重载函数
  • @EmilSakhibgareev remove_if 只将一个参数传递给谓词。所以 std::unique 更适合这样的任务。
猜你喜欢
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
相关资源
最近更新 更多