Reputation: 1
I have this vector with these numbers {0, 1, 0, 3, 2, 3}
and I'm trying to use this approach to have the minimum number and its index:
int min_num = *min_element(nums.begin(), nums.end());
int min_num_idx = min_element(nums.begin(), nums.end()) - nums.begin();
However, this returns the first smallest number it found so the 0
in index 0
. Is there a way to make it return the last smallest number instead? (the 0
in index 2
instead)
Upvotes: 0
Views: 405
Reputation: 3956
However, this returns the first smallest number it found so the 0 in index 0. Is there a way to make it return the last smallest number instead? (the 0 in index 2 instead)
You can try std::vector<int>::reverse_iterator
:
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
int main() {
std::vector<int> n { 0, 1, 0, 3, 2, 3 };
std::vector<int>::reverse_iterator found_it = std::min_element(n.rbegin(), n.rend());
if (found_it != n.rend()) {
std::cout << "Minimum element: " << *found_it << std::endl;
std::cout << "Minimum element index: " << std::distance(n.begin(), std::next(found_it).base()) << std::endl;
}
}
Output:
Minimum element: 0
Minimum element index: 2
Upvotes: 3
Reputation: 9682
int min_num_idx = nums.size() - 1 - min_element(nums.rbegin(), nums.rend()) - nums.rbegin();
Upvotes: 0