1

ベクトルのキューのループで、i 番目のキューの条件が true の場合、その i 番目のキューの queuesize を 5 増やすというパラダイムがあります。この操作の後、すべてのキューのキュー サイズを検索し、最短のキューにエンキューする必要があります。以下のコードのようなことをしたい

#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)
}

条件が真の場合、キューサイズを人為的に増やす方法は? 次に、キューを検索して、最小サイズのキューを見つけます。

更新しました

#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)
}
4

2 に答える 2

3

「キューサイズを増やす」という意味が明確ではありません。

「キューの容量を増やす」という意味であれば、その必要はありません。queue のデフォルトの基礎となるコンテナはdequeです。これはメモリ内の連続したブロックではないため、展開に関する問題は発生せずreserve()、事前に必要がなくなります。詳細については、こちらを参照してください。

したがって、キューのサイズはその中のアイテムの数にすぎません。それを増やしたい場合、 deque には、resize()すべての新しいアイテムの指定された値をパラメーターとして受け取るか、値を初期化するだけの関数があります。

于 2013-02-20T16:21:11.670 に答える
1

これを行う方法を次に示します (C++11 がオプションであると仮定します。そうでない場合、この例はラムダと なしで簡単に書き直せますauto)。

#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);
}
于 2013-02-20T16:17:47.070 に答える