【问题标题】:Creating an array of structures with data entered by the user使用用户输入的数据创建结构数组
【发布时间】:2020-02-16 10:17:55
【问题描述】:

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

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

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

这是我目前所拥有的: 队列.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..?
}

队列.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】:

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

    例如,如果您在类中获取一个结构坐标数组并获取一个整数迭代器,i 来跟踪数组中的当前位置,您可以像这样简单地获取输入:

    cin &gt;&gt; Coordinates[i].x &gt;&gt; Coordinates[i].y, i++;

    【讨论】:

      猜你喜欢
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 2016-01-10
      • 2014-02-26
      • 2017-06-16
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多