Enqueue in a minimum size queue

2019-08-30 09:38发布

问题:

I have a paradigm which has one queue per thread. I wish to find the minimum size queue, among the number of queues, which i did with the following code.

std::vector<std::queue<task> > q;

int min_value = INT_MAX;
std::size_t size = q.size();
for( i=1; i<size; i++){ //accessing loop of queues
  if(min_value > q[i].size())
    min_value = q[i].size();
}

now i wish to do a additional operation in this, every time only the minimum size queue (found from the above code) should enqueue the task.

q.get (min_value)
q.push(task) // will this one, does the required operation?

回答1:

I think what you're looking for is the smallest queue in the vector q. If so, you can do this:

auto cmp = [](std::queue<task> const & a, std::queue<task> const & b) {  
               return a.size() < b.size(); 
           };

//note q is a std::vector of std::queue
auto min_queue = std::min_element(q.begin(), q.end(), cmp);

min_queue->push(item);//min_queue is the iterator to the smallest queue

Also, I believe in your code, i=1 is a mistake, which I think should be i=0 if you want to search the entire vector, i.e from begin to end. If you really mean i=1, then you have to do this:

auto min_queue = std::min_element(q.begin() + 1, q.end(), cmp);

Hope that helps.