i have a paradigm in a loop of queues of a vector,if a condition is true,increase sizes of the queue of that particular queue in the loop of queues, if condition is false, the queuesize is left as such in loop of queues. After this operation i need to search the queue sizes of all queues and enqueue in the shortest queue.
i want to do something like the code given below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <vector>
#include <queue>
int min_index = 0;
std::vector<std::queue<int> > q
std::size_t size = q.size();
for( i=0; i<size; i++){
if(..) {// some condition is true
q[i].size=q[i].size+5
}
else{
q[i].size=q[i].size+0
}
if(q[min_index].size() > q[i].size())
min_index = i; // Now q[min_index] is the shortest queue
}
q[min_index].push(int)
}
can you please help me out how to implement this logic?
will q[i].size=q[i].size+5 increase the queuesize by 5 for the ith queue?
well, i think the task is not to add a value to the queue size.
It makes definitely more sense to add a value to the queue itself (which indeed increases the queue size):
1 2 3
if(..) {// some condition is true
q[i].push(5); // this pushes 5 on the queue and adds 1 to the size
}
@JLBorges
It's good to promote C++11, but it seems a bit more than the OP requested.
I don't like the use of auto. It rather obfuscate the type of a variable
how about using std::deque instead of std::vector as it has a resize() function, which resizes the size of queue.
well, if you replace the vector with a deque how would that affect the queue?
if you want something like q[i].resize(); you need to replace the inner queue with a deque.
is it possible to do like this?
yes, but make it simplier:q[i].resize(q[i].size() + 5)
if you use a function like JLBorges showed above you dont need to change the nature of the queue:
1 2 3 4 5 6 7 8 9 10 11
void increase_queue_size( std::queue<int>& q, int value = 0, std::size_t by = 5 )
{
size_t new_size = q.size() + by ;
while( q.size() < new_size ) q.push(value) ;
}
...
if(...) {// some condition is true
increase_queue_size(q[i]); // increase the size by 5 times
}
...
So shall i use vector of deque's to do the same operation?
It's up to you. deque has push_front/pop_frong and push_back/pop_back instead of just push/pop like queue. So q[min_index].push is not longer valid. You have to decide which push/pop combination
shall i use the boost library to deal with the heterogenous container
boost::variant stores only one value (type) at a time. Either string or int but not both.
So this isn't exactly a ' heterogenous container'.
It has a function which() if you need to decide what data type is used
If you want to keep both you need a struct or class.