Michiel uit het Broek
Michiel uit het Broek

Reputation: 993

Minimum of subset of vector (c++)

I need the index of the minimum value in a vector<int>, however only some indices must be taken into account. Say we have:

vector<int> distance({5, 5, 4, 3, 5});
vector<int> neighbors({0, 1, 2, 4});

Then the value 3 is not taken into account and thus 4 is the minimum value, hence I need index 2. One could solve it by adding a large constant to the values which are not taken into account:

int City::closest(set<int> const &neighbors) const
{
  vector<double> dist(d_distance);
  for (size_t idx = 0; idx != dist.size(); ++idx)
  {
    auto it = find(neighbors.begin(), neighbors.end(), idx);
    if (it == neighbors.end())
      dist[idx] = __INT_MAX__;
  }

  auto min_el = min_element(dist.begin(), dist.end());
  return distance(dist.begin(), min_el);
}

However I my opinion this method is unreadable and I would prefer a STL algorithm or a combination of two of them. Do you have a more neat solution for this?

Upvotes: 2

Views: 331

Answers (2)

Tanmay
Tanmay

Reputation: 404

Is this what you want to do?

 int min=__INT_MAX__;
 int minIndex=-1;
 for(int i=0;i<neighbours.size();i++){

    if(distance[neighbours[i]]<min){
        min=distance[neighbours[i]];
        minIndex=i;
    }
}

Upvotes: 1

ecatmur
ecatmur

Reputation: 157334

Use the variant of min_element taking a comparator, and use neighbors as the range and distance as your cost function:

return *min_element(neighbors.begin(), neighbors.end(),
    [&](int i, int j) { return distance[i] < distance[j]; });

Upvotes: 5

Related Questions