使用用户输入的数据创建结构数组

问题描述 投票:1回答:1

我有一个作业,需要创建一个探究FIFO队列的程序。任务是创建一个数组,其中每个元素包含2个数字x和y。然后,您必须有一个push,pop和show方法,它们可以插入一个新元素,删除一个元素并显示队列中的所有当前元素。

我尝试根据自己的需要调整基本队列系统,但是对于每个元素(x和y)必须具有2个值的部分,我遇到了麻烦。

我最近的尝试是使用结构。但是我在每次选择添加(推送)数据的选项时都难以理解如何创建结构。然后返回当前保存在结构数组中的所有值。如果可能的话。

这是我到目前为止的内容:queue.cpp

#include <iostream>
#include "queue.h"
#include <array>
using namespace std;

queue::queue(){
    int length;
    cout <<"Queue max length: ";
    cin >> length;
    cout <<"\n";

    int array[length];
    capacity = length;
}

void queue::push(){
     struct Coordinates{ //And this whole part wont work either cause I need to create a structure before I can enter data into it. 
//I assume I need to use a for loop in order to createa strcutre everytype the 'push' method is called?
            int x;
            int y;
        }arr[capacity];

for (i = 0; i<capacity; i++){ //Something like this to createa a struct for each array element?

}

    cout << "Please enter the desired values (x, y): ";
    cin >> Coordinates.x >> Coordinates.y;
    cout <<"\n" << "You entered: " <<Coordinates[1]; //This is obviously wrong, I dont actually get how I will print the structures that are saved in the array? And how will I tell the program to assign the values to the first array element, the second, the third etc..?
}

queue.h:

#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>

class queue
{
    public:
        queue();
        virtual ~queue();
        void push();
        void pop();
        void show() const;

    private:
        int capacity;
};

#endif // QUEUE_H 

我很抱歉,如果它太长了,我想如果我把它缩短了,那是没有道理的。

预期的最终结果应如下所示:

Please enter the size of the queue: 15

What would you like to do? + (positive being they have to enter two new numbers)
Please enter the coordinates to be saved: 5,4

What would you like to do? + (again)
Please enter the coordinates to be saved: 3,5

What would you like to do? * (star being show method)

(Show method) The current Queue is: {5,4}, {3,5};


What would you like to do? - (negative being dequeue)

(Show method) The current Queue is: {3,5};


What would you like to do? + (positive being they have to enter two new numbers)
Please enter the coordinates to be saved: 7,8

(Show method) The current Queue is: {3,5}; {7,8};

And so forth. I hope this explains the end results.

任何建议或指向我在做错事的指针,我们将不胜感激。谢谢。

c++ arrays oop struct
1个回答
0
投票

您可以全局创建一个方法,然后在队列类中使用它的数组。您不必每次调用push方法都创建它。在类内部创建一个私有迭代器。在push函数中,您只需输入并将其添加到迭代器编号中即可。结构数组中的元素。

例如,如果您在类中采用了一个结构坐标数组,并且采用了整数迭代器,那么我要跟踪数组中的当前位置,您可以像这样简单地输入:

cin >> Coordinates[i].x >> Coordinates[i].y, i++;

© www.soinside.com 2019 - 2024. All rights reserved.