c++ - 将类对象直接读入c ++中的向量
问题描述
所以我开始学习c++中的向量,并制作了这个程序,但我不喜欢我将对象数据读入C风格的数组,然后将所有数据传输到向量中。是否可以在不使用C 样式数组的情况下将数据读入向量?这是我的代码:
#include <iostream>
#include <vector>
#include <stdlib.h>
using std::cout;
using std::cin;
using std::endl;
class number
{
private:
std::string name;
float n1_;
int n2_;
public:
number() = default;
~number() = default;
public:
void read();
float perMonth(){return n1_ * n2_;}
float perYear(){return perMonth() * 12;}
std::string get_Name(){return name;}
};
void number::read()
{
cout << "Worker name: "; cin >> name;
n1_ = rand() % 100 + 3;
n2_ = rand() % 100 + 3;
}
int main()
{
int n;
cout << "Insert number of workers:"; cin >> n;
number pers[30];
for(int i = 0; i < n; i++)
pers[i].read();
std::vector<number> people;
for(int i = 0; i < n; i++)
people.push_back(pers[i]);
for(number pr : people)
{
cout << "Name: " << pr.get_Name() << endl;
cout << "Salary per month: " << pr.perMonth() << endl;
cout << "Salary per year: " << pr.perYear() << endl << endl;
}
}
解决方案
是的,您可以在不使用数组的情况下将对象放入 std::vector 中。
int main()
{
int n;
cout << "Introduceti numarul de lucratori:"; cin >> n;
std::vector<number> people;
for(int i = 0; i < n; i++)
{
number pers();
pers.read();
people.push_back(per);
}
for(number pr : people)
{
cout << "Name: " << pr.get_Name() << endl;
cout << "Salary per month: " << pr.perMonth() << endl;
cout << "Salary per year: " << pr.perYear() << endl << endl;
}
}
推荐阅读
- javascript - 轮询 Javascript
- ios - Unity 应用程序的 iOS 崩溃
- c# - 使用 Opc.UA.Fx 保存历史数据
- php - 为我的 laravel 项目创建 git 存储库后未跟踪文件
- typescript - 打字稿:如何使用具有结构而不是判别属性的可区分联合?
- python - Python比较两个列表并将值添加到第三个列表
- python - 使用 numpy 和 Scipy 计算三重积分的 Python 程序?
- java - Java sun.net.HttpServer 写入 OutputStream 抛出 IOException “已建立的连接被主机中的软件中止”
- javascript - 在 Laravel API 中获取 HTTP Post Vue 数据
- go - bufio.NewScanner.Scan 挂起程序