如何在队列中存储数组

How to store arrays in queues?

本文关键字:存储 数组 队列      更新时间:2023-10-16

我正在编写一段代码,我想出了一个问题,这是如何在队列中插入数组?让我举个例子来解释你。

array1[9]={1,3,4,2,1,2,3,4,1}
array2[9]={2,3,4,2,4,2,2,2,3}
//create a queue (I don't know how to declare a queue for this issue)...
queue.push(array1);
queue.push(array2);
//##############################
//when I print queue.front()...
//########################
printf("%d",queue.front());

上面的代码片段应该打印 array1 的每个元素!!怎么做??

如果使用 std::array 而不是 C 样式数组,这很容易。

std::array<int, 9> array1 = { 1, 3, 4, 2, 1, 2, 3, 4, 1 };
std::array<int, 9> array2 = { 2, 3, 4, 2, 4, 2, 2, 2, 3 };
std::queue<std::array<int, 9>> queue;
queue.push(array1);
queue.push(array2);
for (auto i : queue.front()) {
    std::cout << i;
}

对于这个问题来说,这个答案太简单了。 如果您需要动态数组大小,只需在您最喜欢的搜索引擎中准确搜索即可:-)

int array1[9]={1,3,4,2,1,2,3,4,1};
int array2[9]={2,3,4,2,4,2,2,2,3};
std::vector<int> a1(9);
std::vector<int> a2(9);
for(int i =0; i< 9;i++){        
    a1[i]=array1[i];
    a2[i]=array2[i];// <= a2[i] should take values from array2[i]
}
std::queue<std::vector<int>> queue;    
queue.push(a1);
queue.push(a2);
//std::cout<<queue.size()<<std::endl;
std::vector<int> temp(9);
int size =queue.size();
for(int i =0; i< size;i++){        
    temp=queue.front();
    std::cout<<"Array["<<i<<"]: ";
    for(int j =0; j< temp.size();j++)
        std::cout<<temp[j]<<",";
    std::cout<<std::endl;
    queue.pop();
}