【问题标题】:How to store user input into vectors with pointers如何使用指针将用户输入存储到向量中
【发布时间】: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 的指针?真的吗?对我的咆哮感到抱歉,但请告诉你的老师,他应该为自己感到羞耻。
  • 我知道的,我经常逃课在家学习,但我还是要做这些任务..

标签: c++ class pointers vector


【解决方案1】:

首先在你的类中为每个元素创建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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多