我有 2 个 double vector :t
和 P
.它们的大小是 m
.
我想检查条件:|t[i]-t[i+1]| < dT
vector t
和 |P[i]-P[i+1]| < dP
vector 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
按索引删除时,这是正确的方法吗? ?
最佳答案
对于这样的任务,最好使用带有谓词的标准算法 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
关于c++ - 如何在 C++ 的循环中从 vector 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48329229/