首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >增加队列大小并找到最短的队列

增加队列大小并找到最短的队列
EN

Stack Overflow用户
提问于 2013-02-20 15:59:37
回答 2查看 2.2K关注 0票数 1

我有一个范例,在向量的队列循环中,如果一个条件对ith队列是正确的,那么将该ith队列的队列大小增加5。在此操作之后,我需要搜索所有队列的队列大小,并在最短队列中加入队列。我想做一些类似下面给出的代码

代码语言:javascript
复制
#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(..) {// A condition is true
 //increase the size of the ith queue by 5 more times
}

if(q[min_index].size() > q[i].size())
        min_index = i; // Now q[min_index] is the shortest queue
} 
q[min_index].push(int)
}

如果条件为真,如何人为地增加队列大小?然后搜索队列并找到最短大小的队列。

更新

代码语言:javascript
复制
#include <vector> 
#include <deque> 
int min_index = 0;
std::vector<std::deque<int> > q
std::size_t size = q.size();
for( i=0; i<size; i++){ 
   if(...) {// A condition is true
  q[i].resize(q[i].size() + 5)
}
if(q[min_index].size() > q[i].size())
        min_index = i; // Now q[min_index] is the shortest queue
} 
q[min_index].push(int)
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-20 16:21:11

您所说的“增加队列大小”是什么意思还不清楚。

如果您的意思是“增加队列的容量”,则不需要这样做。队列的默认底层容器是德克,它不是内存中的连续块,因此在展开时不会遇到任何问题,从而消除了预先对reserve()的需求。有关这方面的更多细节,请参见这里

因此,队列的大小就是它中的项目数。如果您想要增加这个值,deque有一个resize()函数,它为所有新项接受一个指定的值作为参数,或者只是值初始化它们。

票数 3
EN

Stack Overflow用户

发布于 2013-02-20 16:17:47

下面是一种可能的方法(假设C++11是一个选项,否则在没有lambdas和auto的情况下,示例很容易重写):

代码语言:javascript
复制
#include <vector>
#include <queue>
#include <algorithm>

// Don't use this in your real code: I use it here just for convenience.
// It is a bad programming practice to import a whole namespace (especially
// if it is a Standard Library namespace).
using namespace std;

// The function that defines your condition on each queue
bool cond_on_q(queue<int> const& q)
{
    bool satisfied = false;
    // Determine whether the condition is satisfied...
    return satisfied;
}

int main()
{
    vector<queue<int>> v = ...; // Initialize your vector of queues somehow

    // Iterate over the vector of queues
    for (auto& q : v)
    {
        if (cond_on_q(q)) // Is the condition satisfied?
        {
            // Insert 5 elements with any valid value (for instance, 0)
            for (int i = 0; i < 5; i++) (q.push(0));
        }
    }

    // Determine the queue with the minimum size.
    auto i = min_element(begin(v), end(v),
        [] (queue<int> const& q1, queue<int> const& q2) { 
            return q1.size() < q2.size(); 
            }
        );

    int newValue = ...; // Initialize the value to be enqueued somehow.        

    // Add the value to the queue with minimum size.
    i->push(newValue);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14984333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档