【发布时间】:2018-03-21 14:41:05
【问题描述】:
我现在整天都在尝试解决这个任务,但我做不到并且需要一些帮助。 任务是: 编写一个程序,要求用户输入随机人数。对于每个人,输入他们的姓名和年龄,对于公寓 - 房间数量和公寓面积。在屏幕上打印两居室公寓的人名和公寓面积。
注意:每个人的公寓应该是指向 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");
}
【问题讨论】:
-
请将您的代码缩减为minimal reproducible example。还要描述您遇到的确切错误。
-
我没有收到错误(目前),我只是不知道如何将用户输入存储到向量中
-
(顺便说一句,@ 最难的名字)。分配一个
Person*,然后使用vector::push_back?这是一个非常基本的操作,应该在您的课程/书籍/教程中介绍 -
为什么人们发布的所有这些作业问题的设计都如此糟糕?一个
std::vector的指针?真的吗?对我的咆哮感到抱歉,但请告诉你的老师,他应该为自己感到羞耻。 -
我知道的,我经常逃课在家学习,但我还是要做这些任务..