C ++-队列中的最小值

Nik*_*kov 2 c++ queue struct

我有来自结构类型的队列

struct test {
   int numbers;
};

queue<test> q;
Run Code Online (Sandbox Code Playgroud)

如何从中找到最小值:

q.front().numbers;
Run Code Online (Sandbox Code Playgroud)

例如,如果数字中有5,1,3,我需要找到1。

bet*_*ido 5

由于您需要整数队列,因此最简单的解决方案是使用std::deque<int>。然后,您可以std::min_element用来查找队列中的最小元素:

std::deque<int> q{5, 1, 3};
std::deque<int>::iterator it = std::min_element(q.begin(), q.end());
std::cout << *it << std::endl;
Run Code Online (Sandbox Code Playgroud)

这样,您无需使用struct test。这尤其如此,因为它似乎只存储一个整数。另一方面,如果struct test更复杂(具有更多字段),则可以使用完全相同的方法,但要为其定义一个比较函数struct test(有关此类比较函数的示例,请参见@fljx答案)。

如果只能使用a queue,则只能执行的操作类型受到限制。因此,您需要执行以下操作:

std::queue<int> q;
/* fill queue ... */
int min_value = INT_MAX;
std::size_t size = q.size();
while (size-- > 0) {
    int x = q.front();
    q.pop();
    q.push(x);
    if (x < min_value)
        min_value = x;
}
Run Code Online (Sandbox Code Playgroud)

  • @NikolaiCekov如果您只能使用`queue`,那么我能想到的唯一方法是清空循环中的所有队列,并在清空它时跟踪找到的最小元素。但是,如果要在找到最小元素后保留“ queue”,那绝对不是一个好主意。您也可以将弹出的元素再次插入队列中,但是与使用`deque`相比,这是一项昂贵的操作。 (2认同)