Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

c++ - Remove items from two vectors depending on the values inside one vector

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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));
                             });

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());

Live demo


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));
                               });

Live demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...