簡體   English   中英

c++ 遍歷對象數組

[英]c++ loop through array of objects

我是 c++ 的新手,我在遍歷對象數組時遇到了困難。 對象采用這種形式:Class * arr; (在我的例子中:Persons * person_list;)

問題:我不知道如何遍歷 object 數組,我想調用它們的函數,例如,正如你所看到的,我的代碼有 Persons class 和 function printPersonsInfo() 並且我在主文件(array personList)中有數組 decleration ,我希望能夠做類似的事情 for(Persons p: personList) p.printPersonInfo();

嘗試制作多種循環,但大小為 arrays 的循環不成功,目前沒有任何效果。 代碼來了:

主文件:

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;
    }

};

Files.h class,我從文件中讀取數據並將它們生成到 arrays:

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 class 並從文件中讀取,以下是我將信息存儲在 Persons.txt 中的方式:

ID#NAME#SURENAME#PHONE

這個想法是讀取文件,從中創建 arrays 個對象,並將它們傳遞給主要的 class。

如果有任何區別,我將使用 C++14。

謝謝。

您應該只返回一個 std::vector 而不是原始指針。 原始指針不會帶來它指向的元素數量(您需要一個額外的參數)。 然后你可以像往常一樣在向量上迭代。

可以這樣循環遍歷對象數組

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 object "x" 的副本將附加到文件中每一行的向量中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM