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 is 1.8 at index 4.
Here's my solution using a loop
double minVal = std::numeric_limits<double>::max();
int minIndex;
for (size_t i = 0; i < vec.size(); ++i)
{
if (vec[i] < minVal && mask[i] == 1)
{
minVal = vec[i];
minIndex = i;
}
}
But I was wondering if there is a way to do it by using the standard library (e.g. std::min_element and lambdas), ideally without using the for-loop?