根据第一个向量的元素从两个 std::vector 中删除元素
Remove elements from two std::vectors based on the first vector's elements
我必须用相同数量的元素向量。我想根据一个条件删除第一个向量的元素,但我也想从第二个向量中删除位于相同位置的元素。
例如,这里有两个向量:
std::vector<std::string> first = {"one", "two", "one", "three"}
std::vector<double> second = {15.18, 14.2, 2.3, 153.3}
我想要的是删除基于条件,如果元素是"1"。最后的结果是:
std::vector<std::string> first = {"two", "three"}
std::vector<double> second = {14.2, 153.3}
我可以从first
中删除元素,使用:
bool pred(std::string name) {
return name == "one";
}
void main() {
std::vector<std::string> first = {"one", "two", "one", "three"}
first.erase(first.begin(), first.end(), pred);
}
但是我不知道从第二个向量中删除元素的方法。
我建议您更改数据结构。使用一个结构体来保存两个元素:
struct Entry
{
std::string text;
double value;
};
现在它变成了一个包含两个元素的向量:std::vector<Entry> first_and_second;
在vector中搜索给定文本时,可以删除一个同时包含文本和值的元素。
for(int i = first.size() - 1; i >= 0; i--){
if(first[i] == "one"){
first.erase(first.begin() + i);
second.erase(second.begin() + i);
}
}
相关文章:
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 查找两个排序向量中共有的元素
- 关于比较两个无序数组并删除 a[] 中可以在 b[] 中找到的元素的问题
- 为什么两个矢量元素的地址有这么大的差距?
- 高级选择排序 - 在一次迭代中搜索两个元素
- 如何使用谷歌测试检查两个枚举类元素的相等性?
- C++函数返回两个 char 数组的相同索引元素
- 我想创建一个嵌套数组,该数组由另一个数组中的所有元素组成,但分为两个
- 如何仅考虑 *指针中的前两个元素
- 为什么具有两个元素的发起器语法将一个元素而不是两个元素放入字符串向量中?
- 我应该如何使用remove_if删除两个数字范围内的元素
- 是否可以交换在 c++ 中作为函数 func(say) 中的参数传递的 const 向量的两个元素,例如:vector<int>func (const vector<int>&
- C++ std::向量插入两个元素替代算法失败
- 删除两个相邻的元素并用矢量中的单个元素替换它们
- 如何比较C 列表中的两个连续元素
- 通过将两个参数包的元素线程化为类型对来解压缩这两个参数包
- 数组中两个元素的最大异或
- 优化两个 std::vector<std::complex> 的元素乘积,使用 <float>fftw_malloc() 分配
- 我无法将二维数组的两个元素的差异分配给C++中其他数组的元素?
- 一个数组可以划分的最大子数组,使得不同子数组中任意两个元素的 GCD 始终为 1?