从向量中移除最后的元素,直到条件
removing last elements from vector until condition
我遇到了一个问题,我需要删除向量的最后一个元素,直到满足某个条件(为了这个例子,假设元素不是零)
我写了这个代码,它做到了技巧-
auto next = vec.rbegin();
while (next != vec.rend())
{
auto current = next++;
if (*current == 0)
vec.pop_back();
else
break;
}
但我更愿意找到一个可以使用的stl算法(我可以使用find_if,然后擦除,但我想通过我删除的元素循环一次…)
此外,我担心我可能会在这里调用一些UB,我应该担心吗?
您的代码可以更简单:
while( !vec.empty() && vec.back() == 0 )
vec.pop_back();
使用std::remove
或std::remove_if
将删除所有基于标准的元素,因此您应该使用Vlad在其回答中提供的std::find_if
。
下面是一个例子。它使用了擦除矢量的通用习惯用法
v.erase( std::remove( /*...*/ ), v.end() )
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5, 0, 0, 0 };
v.erase(
std::find_if( v.rbegin(), v.rend(),
[]( int x ) { return x != 0; } ).base(), v.end() );
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
输出为
1 2 3 4 5
相关文章:
- 基于多个条件处理地图中的所有元素
- 如果验证容器的大小并在同一条件语句下访问元素,这是很好的做法吗?
- 如何有条件地将元素添加到 std::array - C++11
- 我可以在一行代码中将向量中与条件匹配的所有元素插入到集合中吗?
- 在矢量中使用特定条件检查唯一元素
- 如何在不使用循环或迭代器的情况下检查所有列表元素并在满足条件时删除一个
- AVX2 根据条件将连续元素扩展到稀疏向量?(如AVX512 VP扩展)
- 检查是否所有 std::元组元素都满足条件 + 设计问题
- 在C++中有条件地删除Singly Linked List中的元素
- 在c++中找到满足给定条件的向量的元素的位置
- 传入一个迭代器,该迭代器只迭代满足特定条件的元素
- X宏中元素的条件定义
- 根据条件将元素从 std::vector 复制到 std::set 但它崩溃了
- 根据条件将元素从一个forward_list转移到另一个
- 如何根据另一个向量中的条件从另一个向量中删除元素
- OpenCV 从矩阵中获取条件基最大元素位置
- 如何根据c++11中的特定条件从向量中擦除元素
- 从向量中移除最后的元素,直到条件
- 基于条件语句删除循环中的矢量元素
- 找到满足条件的第n个元素