c ++:将数组推入队列但是只使用std :: Queue弹出一个int形式

时间:2015-05-29 12:30:08

标签: c++ arrays queue

我想用c ++编写BFS Openmp!在Bfs方法中,我需要添加一个int数组(Dynamicly Allocated)

1 int *ptrTempNeighbour;
2 queue <int > Q;
3 firstElement = Q.front();//return front element   
4 Q.pop();//pop an int
5 ptrTempNeighbour = new int[nodesArray[firstElement].numNeighbours];
6 //nodesArray[firstElement].numNeighbours is an int
7 #pragma omp parallel for
8 for(i=0 ; ...){
9 ptrTempNeighbour[i] = nodesArray[firstElement].neighbours[i];
10 }
11 Q.push(ptrTempNeighbour);//add an array to Queue

第11行现在不起作用。我需要向Queue添加(推送或插入)一个数组,但在第3行中我只需返回一个int或pop(Queue)方法只弹出一个int。 我读了can i store array to queue in c++Queue of array of characters的方式 在can i store array to queue in c++中使用此行

queue < int* > qq;

如果我在程序中使用这一行而不是第2行,第3行和第4行对我来说无法正常工作。这行返回给我一个不是单个int的向量。

!!!!编辑帖子!!!!

首先将ptrTempNeighbour(0)添加到Q然后将ptrTempNeighbour(1)添加到Q然后将ptrTempNeighbour(2)添加到Q并且... 我认为优先队列是有帮助的,但我不知道我是如何使用它的!

2 个答案:

答案 0 :(得分:0)

STL容器只能保存单一类型的数据。因此,您可以添加和删除数组或单个值。但是,也许队列队列完成了你希望做的事情:

std::queue< std::queue< int >* > qOfQs; // create a q of ptrs to qs of ints
std::queue< int >* p_q( new std::queue<int> ); //create a q on the heap
p_q->push( 1 ); // add data to the queue
p_q->push( 2 );
p_q->push( 3 );
qOfQs.push( p_q ); // add the dynamic q to the q of qs
p_q = new std::queue<int>; // create another q on the heap
p_q->push( 4 ); // add data to the queue
p_q->push( 5 );
qOfQs.push( p_q ); // add the dynamic q to the q of qs
qOfQs.front()->pop() // removes int with value 1

您需要确保有弹出的数据,当您完成队列队列时,您需要遍历它并删除动态分配的队列,或者更好的是,使用智能指针。

答案 1 :(得分:0)

谢谢Hugh White回答我。这是个好主意,但只能用于串行代码。

在我阅读了一些文章后,我发现这些函数不是线程安全,所以我们不能在并行区域中使用这些函数。

再次感谢!