Remove elements from two vectors based on values ​​within one vector

I have two integer vectors of equal length. Let's say I want to delete all elements in the first vector that are NAN. Obviously I am using the remove_if algorithm. Let's say this removes the elements that were at indices 1,2,5. Then I want to remove elements from the second vector at those indices.

What's the most canonical C ++ way to do this?

+3


source to share


2 answers


This can be done with Boost by creating zip_iterator

and then iterating over the iterators tuple

from both containers in parallel.

Pass a pair from zip_iterators

to first std::remove_if

and the predicate will check 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));
                             });

      

Then use vector::erase

to remove unwanted items.

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

      



Live demo


The pattern required to create iterator gap ranges can be further reduced with boost::combine

the Boost.Range version remove_if

.

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

      

Live demo

+9


source


Use vector<pair<int, int>>

to link two vectors together. Then do a delete based on the first element and get rid of both at the same time.



+1


source







All Articles