c++循环通过对象数组

oalqel3c  于 2023-02-01  发布在  其他
关注(0)|答案(2)|浏览(133)

我是个c++新手,在遍历对象数组时遇到了困难。对象的形式如下:* 类arr;(在我的例子中:人员 * 人员_列表;)
问题:我不知道如何循环遍历对象数组,我想调用它们上的函数,例如,正如你所看到的,我的代码中有Persons类和函数printPersonsInfo(),我在主文件中有数组声明(array personList),我想能够做一些类似于for(Persons p:个人列表)p.打印个人信息();
尝试了很多种循环,循环失败,数组大小也不成功,到目前为止没有任何效果。代码如下:
主文件:

int main()
{

    //reading objects from file into array
    Persons * personList = Files::createPersonsArray();

    //reading objects from file into array
    Auto * autoList = Files::createAutoArray();

    return 0;
}

Object类之一(两者几乎相同):

class Persons
{
public:
    int id;
    string name, surename, phone;

    Persons() {
        //required empty constructor
    }

    Persons(int i, string n, string s, string p) {
        this->id = i;
        this->name = n;
        this->surename = s;
        this->phone = p;
    }

    void printPersonInfo() {
        cout << endl;
        cout << "ID : " << id << endl;
        cout << "Name : " << name << endl;
        cout << "Surename : " << surename << endl;
        cout << "Phone : " << phone << endl;
    }

};

h类,在这里我从文件中读取数据并将它们生成数组:

class Files
{
public:

    static Persons * createPersonsArray() {

        string textLine;

        // Read from the text file
        ifstream PersonsFile("Persons.txt");

        //counter
        int count = 0;
        //counting records in file
        while (getline(PersonsFile, textLine))
            count++;

        //return to start of file
        PersonsFile.clear();
        PersonsFile.seekg(0, ios::beg);

        //making array of persons
        Persons* person_list = new Persons[count];

        //total persons found
        cout << "Lines of persons :" << count << endl;

        int i = 0;
        // Use a while loop together with the getline() function to read the file line by line
        while (getline(PersonsFile, textLine)) {

            //explodes line of person info into parts
            auto parts = explode(  textLine,'#');

            //stoi converts ID from string to int
            person_list[i] = Persons(stoi(parts[0]), parts[1], parts[2], parts[3]);

            //increased counter
            i++;
        }

        // Close the file
        PersonsFile.close();

        return person_list;
    }

    static Auto* createAutoArray() {

        string textLine;

        // Read from the text file
        ifstream AutoFile("Auto.txt");

        //counter
        int count = 0;
        //counting records in file
        while (getline(AutoFile, textLine))
            count++;

        //return to start of file
        AutoFile.clear();
        AutoFile.seekg(0, ios::beg);

        //making array of persons
        Auto* auto_list = new Auto[count];

        //total persons found
        cout << "Lines of autos :" << count << endl;

        int i = 0;
        // Use a while loop together with the getline() function to read the file line by line
        while (getline(AutoFile, textLine)) {

            //explodes line of person info into parts
            auto parts = explode(textLine, '#');

            //stoi converts ID from string to int
            auto_list[i] = Auto(stoi(parts[0]), stoi(parts[1]), stoi(parts[2]), parts[3], parts[4], parts[5]);

            //increased counter
            i++;
        }

        // Close the file
        AutoFile.close();

        return auto_list;
    }

    //explode function
    static vector<string> explode(string const& s, char delim)
    {
        vector<string> result;
        istringstream iss(s);

        for (string token; getline(iss, token, delim); )
        {
            result.push_back(move(token));
        }

        return result;
    }

    //find owner info based on id
    static void findCarOwnerInfo(int id) {

        string textLine;

        // Read from the text file
        ifstream PersonsFile("Persons.txt");

        //if file is not empty
        if (PersonsFile.peek() != ifstream::traits_type::eof()) {

            //counting records in file
            while (getline(PersonsFile, textLine)) {
                 auto parts = explode(textLine, '#');

                 //if person id matches
                 if (stoi(parts.at(0)) == id) {
                     cout << endl;
                     cout << "(ID:"<<parts.at(0)<<") Owner info ---------" << endl;
                     cout << "Name : " << parts.at(1) << endl;
                     cout << "Surename : " << parts.at(2) << endl;
                     cout << "Phone : " << parts.at(3) << endl;
                 }
            }
        }
        else {
            cout << "error finding persons." << endl;
        }
    }
};

因为我共享了Persons类并从文件中阅读,所以下面是我如何在Persons.txt中存储信息的:

ID#NAME#SURENAME#PHONE

其思想是读取文件,从中创建对象数组,并将其传递给主类。
我使用C++14,如果这有什么区别的话。
谢谢。

h43kikqp

h43kikqp1#

你只需要返回一个std::vector而不是一个raw指针。raw指针并不带着它所指向的元素数量(你需要一个额外的参数)。然后你可以像往常一样在vector上迭代。

eblbsuwk

eblbsuwk2#

循环通过对象数组可以这样完成

Persons personList[constSize];
for (int i=0; i<=constSize; ++i){
    personList[i].func();
}

或者不确定数组的必要大小

vector<Persons> personList;
Persons x;
while(getline(PersonsFile, textLine)){
    personList.pushback(x);
}
personList[0].func();

Persons对象“x”的副本将附加到文件中每一行的向量。

相关问题