Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing max/min int in set for c++

Tags:

c++

function

set

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();
like image 572
Valrok Avatar asked Feb 22 '14 20:02

Valrok


People also ask

Is there a MIN MAX function in C?

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).

How do you find the largest element in a set?

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.

What is MAX () and MIN ()?

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.


2 Answers

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();
like image 111
Joseph Mansfield Avatar answered Oct 03 '22 11:10

Joseph Mansfield


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.

like image 27
Avt Avatar answered Oct 03 '22 11:10

Avt