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

时间:2018-03-21 14:41:05

标签: c++ class pointers vector

我现在整天都试图解决这个问题,但我不能帮助你。 任务是: 编写一个程序,要求用户输入随机数。为每个人输入他们的姓名和年龄,以及公寓 - 房间数量和公寓面积。在屏幕上打印两室公寓和公寓区域的人的姓名。

注意:每个人的公寓都应该是指向Person类中Class Apartment中对象的指针。控制台输入的人员应存储在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");
}

1 个答案:

答案 0 :(得分:0)

首先在类中为每个元素创建setter。

其次你的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

}