简体   繁体   中英

Is there a way to make a queue using array of structs using c++?

I was wondering how to make an array of structs into queue. For example the structs are:

struct Book
{
    string name;
    int bookID;
    string dateRent;
};

book list[5]; //declare array of structs

How can I make the struct as a queue? The queue supposedly has all three data.

std::queue<Book> q;

Book b1 = {"Book One", 1, "01012020"}; 
Book b2 = {"Book Two", 2, "01012021"}; 

q.push(b1); 
q.push(b2); 

Book top_book = q.front(); 

cout << "top_boook_in_the_queue: " << top_book.name << " " << top_book.bookID << " " << top_book.dateRent << endl;

Well, if im understanding this right. You wish to create array of structure Book.

struct Book
{
    string name;
    int bookID;
    string dateRent;
};

Book arr[10];

This would be array of 10 elements for given structure Book in c++.

You can also create dynamic array like this

Book* arr;
arr = new Book[10];

You can access elements like this

arr[0].name;
arr[0].bookID;
arr[0].rentDate;

If you wish to create c++ structure that acts like a FIFO queue, you will have to create something like this

struct Book
{
    string name;
    int bookID;
    string dateRent;
};

struct BookQueue {
    Book arr[10];
    int size = 0;
    void insert(Book book) {
        if (size == 10) return;
        for (int i = size-1; i >= 0; i--) {
            arr[i + 1] = arr[i];
        }
        arr[0] = book;
        size++;
    }
    Book remove() {
        if (size < 0) return arr[0]; //it should throw error here
        size--;
        return arr[size];
    }
};

NOTE: This is bad for queue, but it is a structure queue, the simple one. For starters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM