C++ - 队列中的最小值

标签 c++ struct queue

我有来自结构类型的队列

struct test {
   int numbers;
};

queue<test> q;

如何找到最小值:

q.front().numbers;

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

最佳答案

因为您需要一个整数队列,所以最简单的解决方案是使用 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;

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

如果你只能使用一个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;
}

关于C++ - 队列中的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11100187/

相关文章:

c++ - 返回值后删除指针

c++ - 转换(const char*)var出错

C++ 套接字服务器 - 无法使 CPU 饱和

c++ - 如何将匿名 C++ union 与匿名结构一起使用

sockets - Laravel Forge 队列 worker

C++ 初始化非静态成员数组

c++ - 固定宽度结构 C++

c - 为什么我得到 "arithmetic of pointer type is required"?

Python 线程/队列问题

python - 名称错误 : name 'self' is not defined - when trying to post values to different queues