首页 > 解决方案 > 将类对象直接读入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;
    }
}


标签: c++vector

解决方案


是的,您可以在不使用数组的情况下将对象放入 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;
        }
    }

推荐阅读