In: Computer Science
C++ How to make this code take a class object instead of int for the vector queue and be able to enqueue and dequeue the object? #include <iostream>
#include <float.h>
#include <bits/stdc++.h>
using namespace std;
void print_queue(queue<int> Q) //This function is used to print queue
{
while (!Q.empty())
{
cout<< Q.front() << " ";
Q.pop();
}
}
int main()
{
int n = 10;
vector< queue<int> > array_queues(n); //Create vector of queues of size 10, each entry has a queue of type int
array_queues[0].push(3); //Push elements into queue at 0th index of vector
array_queues[0].push(4);
array_queues[0].push(5);
array_queues[3].push(11); //Push elements into queue at 3rd index of vector
array_queues[3].push(1);
array_queues[3].push(8);
array_queues[6].push(31); //Push elements into queue at 6th index of vector
array_queues[6].push(55);
array_queues[6].push(101);
array_queues[6].push(-221);
cout<<"\n\n";
for(int i = 0; i < n; i++) //For each element of vector, print its queue
{
cout << "index = " << i << ", Queue: ";
print_queue(array_queues[i]);
cout << endl;
}
array_queues[6].pop(); //Dequeuing elements from queue at 6th index of vector
cout<<"\n\nAfter Dequeuing from 6th index\n";
for(int i = 0; i < n; i++) //For each element of vector, print its queue
{
cout << "index = " << i << ", Queue: ";
print_queue(array_queues[i]);
cout << endl;
}
return 0;
}
//Modified C++ code
#include <iostream>
#include <float.h>
#include <bits/stdc++.h>
using namespace std;
class Integer{
private:
int data;
public:
Integer(int data){
this->data =
data;
}
int getData(){
return
data;
}
};
void print_queue(queue<Integer> Q){
while (!Q.empty()){
cout<< Q.front().getData()
<< " ";
Q.pop();
}
}
int main()
{
int n = 10;
vector< queue<Integer> > array_queues(n); //Create
vector of queues of size 10, each entry has a queue of type
int
Integer num1(3);
Integer num2(4);
Integer num3(5);
Integer num4(11);
Integer num5(1);
Integer num6(8);
Integer num7(31);
Integer num8(55);
Integer num9(101);
Integer num10(-221);
array_queues[0].push(num1); //Push elements into queue at 0th index of vector
array_queues[0].push(num2);
array_queues[0].push(num3);
array_queues[3].push(num4); //Push elements into queue at 3rd index of vector
array_queues[3].push(num5);
array_queues[3].push(num6);
array_queues[6].push(num7); //Push elements into queue at 6th index of vector
array_queues[6].push(num8);
array_queues[6].push(num9);
array_queues[6].push(num10);
cout<<"\n\n";
for(int i = 0; i < n; i++) //For each element of vector, print its queue
{
cout << "index = " << i << ", Queue: ";
print_queue(array_queues[i]);
cout << endl;
}
array_queues[6].pop(); //Dequeuing elements from queue at 6th index of vector
cout<<"\n\nAfter Dequeuing from 6th index\n";
for(int i = 0; i < n; i++) //For each element of vector, print its queue
{
cout << "index = " << i << ", Queue: ";
print_queue(array_queues[i]);
cout << endl;
}
return 0;
}