我有来自结构类型的队列
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/