简体   繁体   English

c++ 遍历对象数组

[英]c++ loop through array of objects

Im newbie in c++ and im having hard times with looping through array of objects.我是 c++ 的新手,我在遍历对象数组时遇到了困难。 Objects are in this form: Class * arr;对象采用这种形式:Class * arr; (in my case: Persons * person_list; ) (在我的例子中:Persons * person_list;)

PROBLEM: I have no idea how to loop through object array, i want to call functions on them, for example, as you can see my code has Persons class with function printPersonsInfo() and i have array decleration in main file ( array personList), i want to be able to do something like for(Persons p: personList) p.printPersonInfo();问题:我不知道如何遍历 object 数组,我想调用它们的函数,例如,正如你所看到的,我的代码有 Persons class 和 function printPersonsInfo() 并且我在主文件(array personList)中有数组 decleration ,我希望能够做类似的事情 for(Persons p: personList) p.printPersonInfo();

Tried to make many kind of loops, unsuccessful for loops with unsuccessful size of arrays, nothing works so far.尝试制作多种循环,但大小为 arrays 的循环不成功,目前没有任何效果。 Here comes the code:代码来了:

Main file:主文件:

int main()
{

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

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

    return 0;
}

One of Object classes ( both are pretty much the same): 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, where i read data from files and generate them into arrays: 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;
        }
    }
};

Since i shared Persons class and reading from files, here is how i store my info in Persons.txt:由于我共享了 Persons class 并从文件中读取,以下是我将信息存储在 Persons.txt 中的方式:

ID#NAME#SURENAME#PHONE

The idea is to read files, create arrays of objects from them and pass them to the main class.这个想法是读取文件,从中创建 arrays 个对象,并将它们传递给主要的 class。

Im using C++14 if that makes any difference.如果有任何区别,我将使用 C++14。

Thanks.谢谢。

You should just return a std::vector instead of a raw pointer.您应该只返回一个 std::vector 而不是原始指针。 The raw pointer do not brings with it the number of elements it points to (you'd need an extra parameter for that).原始指针不会带来它指向的元素数量(您需要一个额外的参数)。 Then you can iterate as usual on the vector.然后你可以像往常一样在向量上迭代。

Looping through an array of objects can be done as such可以这样循环遍历对象数组

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

or if you are unsure of the necessary size of the array或者如果您不确定数组的必要大小

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

A copy of the Persons object "x" will be appended to the vector for each line in your file. Persons object "x" 的副本将附加到文件中每一行的向量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM