gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:31:28 25 4
gpt4 key购买 nike

我有一项任务需要创建一个探索 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.

如有任何建议或指出我做错了什么,我们将不胜感激。谢谢。

最佳答案

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

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

cin >> 坐标[i].x >> 坐标[i].y, i++;

关于c++ - 使用用户输入的数据创建结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58467425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com