Say that I have the following example using a set in c++:
set <int> a;
for (int i = 0; i <10; i++){
//Assume i is a random number
a.insert(i);
}
How can you find the maximum and minimum values for the set example shown above? Ideally I thought that the following would work but it gives the following error:
error: cannot convert 'std::_Rb_tree_const_iterator<int>' to 'int' in assignment
I'm using the following functions to try getting max/min:
min = a.begin();
max = a.end();
The min and max functions are declared in the standard C++ algorithm header by the C++ Standard Template Library (STL). The fmin and fmax functions are included in the standard C math. h header according to the C standard (C99).
rend() methods Approach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set. rend() and set.
The min is simply the lowest observation, while the max is the highest observation. Obviously, it is easiest to determine the min and max if the data are ordered from lowest to highest. So for our data, the min is 13 and the max is 110.
First of all, begin
and end
return iterators, which you need to perform indirection on (*
) to get the element they point at.
Secondly, end
returns the past-the-end iterator, so doesn't actually refer to the last element. You can instead use the reverse begin iterator.
min = *a.begin();
max = *a.rbegin();
a.begin()
and a.end()
are iterators, not elements. Use
min = *a.begin();
to receive min element and
max = *a.rbegin();
to receive max.
max = *a.end();
will not work because it points on the next element after the last one. So it will return garbage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With