Reputation: 6440
I want to calculate a minimum value among a set of values using a custom comparator. At the moment my code looks approximately like this:
SomeStructure best;
for (int i = 0; i < 100; ++i)
{
SomeStructure cur = getValue(i);
if (isLess(cur, best))
{
best = cur;
}
}
I find this way not very explicit. For example, if I used a standard comparer, I could write this much prettier:
accumulator_set<SomeStructure, stats<tag::min>> min;
for (int i = 0; i < 100; ++i))
{
min(getValue(i));
}
extract::min(min);
So, the question is: how can I write something like the second example, but using a custom comparator?
My project uses C++14
and boost
, so the solution can use their features.
C++17
is interesting, though not very useful.
UPDATE: looks like I was not very precise in this question.
getValue
is a complicated function calculating some value given its index, not just retrieving it from a container.std::min_element
, but I'm sure there's any explicit method without doing this.Upvotes: 2
Views: 119
Reputation: 50550
You can use std::min
if you wants to compare two elements or a set of elements contained in an initializer_list
, along with a custom comparator.
See here for further details. There is also a bunch of examples.
Otherwise, you can use std::min_element
for a range. Here the documentation.
EDIT
As far as I understand from your question/comments, you don't have a container on which to iterate, instead you would like to compare a set of unrelated values.
It follows an example, that is the one available in the documentation slightly reduced:
std::min( { "foo", "bar", "hello" },
[](const std::string& s1, const std::string& s2) {
return s1.size() < s2.size();
});
Use your variables instead and create the initializer list on-the-fly, no need for a container anymore.
EDIT 2
In regarding of the update of the question, it follows a possible solution.
You can compare two elements at a time while you iterate over the whole set. As an example, put the first element in a variable called min
, then for each subsequent element compare min
with the currently one you are elaborating and, if the former is greater than the latter, updated the min
variable.
When the iteration ends, you have the min
properly set with the element you were looking for. In this case, std::min
with a custom comparator seems to be the best solution.
Upvotes: 3
Reputation: 27577
Simply use std::min
, something like (assuming you've defined operator<
) :
SomeStructure best;
for (int i = 0; i < 100; ++i)
best = std::min(best, getValue(i));
Upvotes: 1