在c ++的set中引用max / min int

时间:2022-10-25 18:57:09

Say that I have the following example using a set in c++:

假设我在c ++中使用set有以下示例:

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();

2 个解决方案

#1


10  

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.

其次,end返回last-the-end迭代器,因此实际上并不引用最后一个元素。您可以改为使用反向开始迭代器。

min = *a.begin();
max = *a.rbegin();

#2


4  

a.begin() and a.end() are iterators, not elements. Use

a.begin()和a.end()是迭代器,而不是元素。使用

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.

将无法工作,因为它指向最后一个元素之后的下一个元素。所以它会返回垃圾。

#1


10  

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.

其次,end返回last-the-end迭代器,因此实际上并不引用最后一个元素。您可以改为使用反向开始迭代器。

min = *a.begin();
max = *a.rbegin();

#2


4  

a.begin() and a.end() are iterators, not elements. Use

a.begin()和a.end()是迭代器,而不是元素。使用

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.

将无法工作,因为它指向最后一个元素之后的下一个元素。所以它会返回垃圾。