如何使用指针将用户输入存储到向量中

How to store user input into vectors with pointers

本文关键字:存储 向量 输入 用户 何使用 指针      更新时间:2023-10-16

我现在一整天都在尝试解决这项任务,但我就是不能,需要一些帮助。任务是:编写一个要求用户输入随机人数的程序。对于每个人,请输入他们的姓名和年龄,对于公寓,请输入房间数量和公寓面积。在屏幕上打印拥有两室公寓的人的名字和公寓面积。

注意:每个人的公寓应该是指向 Person 类中类公寓中对象的指针。控制台输入的人员应存储在 Vector 中,其中包含指向类 Person 中的对象的指针。

我对指针和向量感到困惑。到目前为止,他是我的代码。我知道这很混乱和糟糕。

#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <algorithm>
using namespace std;
class Apartment {
private:
     int nRooms; // - number of rooms
    double q; // - area of apartment
public:
    Apartment(int nr, double qq)
    {nRooms = nr; q = qq;}
    int get_nRooms() { return nRooms; }
    double get_q() { return q; }
};
class Person{
private:
    string name;
    int age;
    Apartment* apartment;
public:
    Person(string n, int a, Apartment* ap)
    {name = n; age = a; apartment = ap;}
    string getName(){return name;}
    int getAge(){return age;}
    Apartment* setApartment(Apartment *);
    Apartment* getApartment(){return apartment;}
};
int main() {
    vector<Person*> ps;
    string n; // - person's name
    int age, nr; // nr - number of rooms
    double q; // area of apartment
while (cin >> n >> age >> nr >> q){
    if (nr == 2) {
        cout << "People with 2 room apartments:" << n << " " << endl;
        cout << "And their quadrature: " << q << endl;
        } 
}
system("pause");
}
首先,

在你的类中为每个元素创建资源库。

其次,你的while循环逻辑是有缺陷的。做这样的事情

char continue_or_not c = 'y';
while(c == 'y')
{
  \Take input by cin of each element
  \make a temp person pointer
  \make a new person and assign it all the values you input
  \assign that person to that pointer
  \copy that pointer to the vector (you will need a copy constructor for person as well because it has a pointer in it)
  \take input in 'c' again and each iterating
}