[英]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. 假设我要删除第一个向量中NAN的所有项。 Obviously, I use the remove_if algorithm. 显然,我使用remove_if算法。 Let's say this removes elements that were at indexes 1,2,5. 让我们说这会删除索引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? 这种规范的C ++最常用的方法是什么?
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_iterator
使用Boost来完成,然后并行迭代两个容器的迭代器tuple
。
First pass a pair of zip_iterators
to std::remove_if
, and have the predicate inspect the elements of the first vector
for NaN 首先将一对zip_iterators
给std::remove_if
,并让谓词检查NaN的第一个vector
的元素
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. 然后使用vector::erase
删除不需要的元素。
v1.erase(boost::get<0>(result.get_iterator_tuple()), v1.end());
v2.erase(boost::get<1>(result.get_iterator_tuple()), v2.end());
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
. 通过使用boost::combine
和Boost.Range的remove_if
版本,可以进一步减少创建压缩迭代器范围所需的样板。
auto result = boost::remove_if(boost::combine(v1, v2),
[](boost::tuple<double, int> const& elem) {
return std::isnan(boost::get<0>(elem));
});
Use a vector<pair<int, int>>
to tie the two vector together. 使用vector<pair<int, int>>
将两个向量绑定在一起。 Then, perform your remove based on the first element to and get rid of both at the same time. 然后,根据第一个元素执行删除并同时删除它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.