I have a vector of some values and a mask vector of 0’s and 1’s. For example:
std::vector<int> mask{0, 0, 1, 0, 1, 1, 0};
std::vector<double> vec{7.1, 1.0, 3.2, 2.0, 1.8, 5.0, 0.0};
and I need to find the min element (its index) in vec but only where mask is 1. In this example it would be 1.8 at index 4. Is there a way to do it by using the standard library (e.g. std::min_element and lambdas)?
>Solution :
You can make a helper class that’ll combine those vectors into a single vector of structs to make it easy to use min_element:
template <typename T>
class Masker {
private:
template <typename V>
struct Item {
bool mask;
V val;
};
std::vector<Item<T>> vec;
public:
Masker(std::vector<bool> mask, std::vector<T> vals) {
for(size_t i = 0; i < vals.size(); i++) {
vec.push_back({mask[i], vals[i]});
}
}
const T& find_min() {
return (*min_element(vec.begin(), vec.end(),
[](const auto& lhs, const auto& rhs){
if(!lhs.mask) { return false; }
if(!rhs.mask) { return true; }
return lhs.val < rhs.val;
})).val;
}
};
And then call it like:
std::cout << Masker<double>(mask, vec).find_min();
Live example: https://ideone.com/G6ymGH