heeat
heeat

Reputation: 158

How calculation of std::distance works when multiple values with same value are part of the std::vector

    vector<int> arr;

    max = *max_element(begin(arr), end(arr));
    min = *min_element(begin(arr), end(arr));

    auto it = find(arr.begin(), arr.end(), max);
    auto it2 = find(arr.begin(), arr.end(), min);

    dis1 = distance(arr.begin(), it);
    dis2 = distance(arr.begin(), it2);

I wanted to find the indexes of a max and min values in the vector, so I took iterator and used distance method to compute the value.

This works for some inputs but I came across an Input where there are two min values. Input : 10 10 58 31 63 40 76

So here 10 is minimum value but there are 2 10's but I want the distance calculated from the last occurrence of 10 not the first.

I can do this easily by holding a variable and check min values every iteration in a for a loop.

But, I would like to know if I can manipulate the std:: distance some way that program will take the distance from the last occurrence of 10.

Thanks.

Upvotes: 0

Views: 294

Answers (2)

Equod
Equod

Reputation: 556

You can provide a custom compare operator for std::max_element and for std::min_element. Using std::less_equal instead of the default std::less allows you get the last occurrence instead of first:

auto it = max_element(begin(arr), end(arr), std::less_equal<>());
auto it2 = min_element(begin(arr), end(arr), std::less_equal<>());

Example here

Upvotes: 2

Surt
Surt

Reputation: 16129

Find the last occurrence

auto it = find(arr.rbegin(), arr.rend(), max);
auto it2 = find(arr.rbegin(), arr.rend(), min);

Using the reverse iterators should do what you want, finding the last occurrences.

dis1 = distance(arr.begin(), it.base())-1;
dis2 = distance(arr.begin(), it2.base())-1;

If I remember correctly, else test :)

Upvotes: 0

Related Questions