如何使用指针将用户输入存储到向量中
How to store user input into vectors with pointers
我现在一整天都在尝试解决这项任务,但我就是不能,需要一些帮助。任务是:编写一个要求用户输入随机人数的程序。对于每个人,请输入他们的姓名和年龄,对于公寓,请输入房间数量和公寓面积。在屏幕上打印拥有两室公寓的人的名字和公寓面积。
注意:每个人的公寓应该是指向 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
}
相关文章:
- 访问存储在向量C++中的结构的多态成员
- 添加存储在向量中的大整数的函数出现问题
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 如何从用户那里获取输入并将其存储在向量中?
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 在二维向量或数组中可以存储的最大元素数是多少?
- 存储在堆分配向量中的指针的免费存储
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- Sqlite3:将数据库表名存储在向量中
- 如何在数组和向量 c++ 中存储和保存输入
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 是否可以在类中存储unique_ptr,并在C++中存储向量?
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- 在固定大小的向量中存储指向元素的指针
- 无法将派生类存储在基类指针的向量中
- 如何访问和存储向量类型的结构成员
- 如何按索引存储向量的向量
- findnonzero() 中存储向量<Point>中非零元素的坐标时出错