2

I'm trying to create a queue of 2D vectors and see the contents of it each time I push a vector. I tried to implement this and print it with the idea of printing 2D vectors in my head. I have also tried some templates online.

Apparently, it does not work that way for a queue of 2D vectors. I also do not understand the error message as I'm still very new to C++ so I did not know how to fix this or why it is not allowed.

This is what I have tried which does not work:

#include <iostream>
#include <vector>
#include <queue>
#include <string>

using namespace std;

int main()
{
    vector<vector<char>> v = {{'a','b'},{'c','d'}};

    queue<vector<vector<char>>> my_queue;
    my_queue.push(v);

    /*for (unsigned int i = 0; i < my_queue.size(); i++) {
        cout << my_queue.front() << " ";
        my_queue.pop();
    }
    cout << endl;*/

    for (unsigned int i = 0; i < my_queue.size(); i++) {
        for (unsigned int j = 0; j < my_queue[i].size(); j++) {
            cout << my_queue.front() << " ";
            my_queue.pop();
        }
        cout << endl;
    }

    return 0;
}

EDIT

the part of the error message that I do not understandis:

main.cpp:34:9: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘__gnu_cxx::__alloc_traits > >>::value_type {aka std::vector >}’) cout << my_queue.front() << " ";

Any thoughts would help.

EDIT 2: SOLUTION

I have finally found a way to do this after many trials and it works fine for my case:

void State::PrintQueue(queue<vector<vector<char>>> q){
    if (q.empty()){
        cout << "\n[Queue is empty!]" << endl;
        return;
    }
    vector<vector<char>> x = q.front();
    q.pop();
    for (auto& row : x) {
        for (auto& s : row) {
            cout << s << ' ';
        }
        cout << endl;
    }
    cout << endl;
    PrintQueue(q);
    q.push(x);
}

However !, this does not seem to be very efficient.

I would also like to know if there is a way to make a template for this? I have tried all templates out there and I'm still very inexperienced with templates.

kaMOON
  • 105
  • 10

1 Answers1

0

the error message should be enough..

error: no match for ‘operator[]’ (operand types are ‘std::queue’ and ‘int’)

there is no my_queue[x]

you need to do something like

while (!my_queue.empty())
{
    // your logic
    my_queue.pop();
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • I have edited my post with the first way I have tried for printing, my two for loops is sth i have tried since the first method did not work and gave the error that I added to my post. Using the two for loops gives the obvious error you stated here. sorry for confusion – kaMOON Feb 26 '21 at 11:54