根据一个向量内的值从两个向量中删除项 [英] Remove items from two vectors depending on the values inside one vector

查看:123
本文介绍了根据一个向量内的值从两个向量中删除项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相等长度的整数向量。让我们说,我想删除第一个向量中的所有项目是NAN。显然,我使用remove_if算法。让我们假设这将删除在索引1,2,5的元素。然后,我要在这些索引中从第二个向量中删除项目。

I have two integer vectors of equal length. Let's say I want to remove all items in the first vector which are NAN. Obviously, I use the remove_if algorithm. Let's say this removes elements that were at indexes 1,2,5. I then want to remove items from the second vector at these indexes.

这是最经典的C ++方法是什么?

What's the most canonical C++ way of doing this?

推荐答案

这可以使用Boost通过创建 zip_iterator ,然后从两个容器中并行迭代 tuple

This can be done using Boost by creating a zip_iterator and then iterating over the tuple of iterators from both containers in parallel.

首先将一对 zip_iterators 传递给 std :: remove_if ,并使谓语检查NaN的第一个向量的元素

First pass a pair of zip_iterators to std::remove_if, and have the predicate inspect the elements of the first vector for NaN

auto result = std::remove_if(boost::make_zip_iterator(boost::make_tuple(v1.begin(), v2.begin())),
                             boost::make_zip_iterator(boost::make_tuple(v1.end(),   v2.end())),
                             [](boost::tuple<double, int> const& elem) {
                                 return std::isnan(boost::get<0>(elem));
                             });

然后使用 vector :: erase 不需要的元素。

Then use vector::erase to remove the unneeded elements.

v1.erase(boost::get<0>(result.get_iterator_tuple()), v1.end());
v2.erase(boost::get<1>(result.get_iterator_tuple()), v2.end());

现场演示

创建压缩迭代器范围所需的样板文件可以进一步使用 boost :: combine 和Boost.Range的版本 remove_if

The boilerplate required to create the zipped iterator ranges can be further reduced by using boost::combine and Boost.Range's version of remove_if.

auto result = boost::remove_if(boost::combine(v1, v2),
                               [](boost::tuple<double, int> const& elem) {
                                    return std::isnan(boost::get<0>(elem));
                               });

现场演示

这篇关于根据一个向量内的值从两个向量中删除项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆