如何在C++的循环中从矢量中删除元素
How to remove elements from vector in the cycle in C++
我有 2 个双精度向量:t
和 P
。它们的大小是 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
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 从矢量中删除元素后出现隔离错误
- 如何使用remove_if从矢量中删除元素
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- C++映射不删除元素
- 如何从标准::元组中删除元素?
- 在动态数组中添加/删除C++元素
- 如何通过比较彼此的成员从QStringList中删除元素
- 如何修复从矢量中删除元素的错误?
- 从 std::set 中删除元素,同时在 C++17 中迭代该元素
- 使用remove_if从矢量中删除元素
- 用C++从三维矢量中删除元素
- 从对象数组中删除元素
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- C++ - 按自定义数据类型向量的值删除元素
- 从任意容器中廉价删除元素的惯用方法?
- 从数组中删除元素不起作用的函数
- 删除元素 BST
- 从向量中删除元素时未处理的异常