Nikolai Cekov
Nikolai Cekov

Reputation: 167

C++ - Min value in queue

I have queue from struct type

struct test {
   int numbers;
};

queue<test> q;

how to find min value from:

q.front().numbers;

For example if in numbers have 5,1,3 I need to found 1.

Upvotes: 4

Views: 11472

Answers (2)

betabandido
betabandido

Reputation: 19704

Since you need a queue of integers the easiest solution is to use std::deque<int>. Then you could use std::min_element to find the minimum element in the queue:

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

By doing so, you do not need to use the struct test. This is especially true since it seems to just store an integer. If, on the other hand, struct test is more complex (having more fields) then you can use exactly the same approach but defining a compare function for struct test (see @fljx answer for an example of such a compare function).

If you can only use a queue you are restricted on the type of operations that you can do. Therefore, you would need to do something like:

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;
}

Upvotes: 6

j4x
j4x

Reputation: 3716

There is a bunch of pages explaining it around the web.

You need to create an operator < telling how your structure is to be compared.

struct test {
   int numbers;

    bool operator < ( const test &t ) const
    { return this->numbers < t.numbers; }
};

(I haven't tested this code for any silly error, but the links bellow may help if you find any problem).

After then, use #include <algorithm> to have access to min_element().

References: http://www.cplusplus.com/reference/algorithm/min_element/ http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html

Upvotes: 0

Related Questions