结构向量:添加元素 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15850459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:49:03  来源:igfitidea点击:

Vector of structs: adding elements C++

c++vectorstruct

提问by Whizzil

I am reading my structs from a file, and I would like to add them to vector of structs. Here is how it looks and works:

我正在从文件中读取我的结构,我想将它们添加到结构向量中。这是它的外观和工作原理:

    typedef struct
{
    int ID;
    string name;
    string surname;
    int points;
}
Student;

int main()
{
    ifstream theFile("test.txt");
    std::vector<Student*> students;

    Student* s = new Student();

    while(theFile >> s->ID >> s->name >> s->surname >> s->points)
    {
        studenti.push_back(s); // here I would like to add this struct s from a file
    }

// here I want to print each struct's values on the screen, but the output is always ONLY last struct N times, and not all of them, each only once


    std::vector<Student*>::const_iterator it;
    for(it = students.begin(); it != students.end(); it+=1)
    {
        std::cout << (*it)->ID <<" " << (*it)->name << " " << (*it)->surname <<" " << (*it)->points <<endl;
    }

What should I do so I can add my structs to a vector, and print them out normally (this print is only a check really, if the structs are properly loaded into vector)?

我应该怎么做才能将我的结构添加到向量中,并正常打印它们(如果结构正确加载到向量中,此打印实际上只是一个检查)?

回答by john

Your mistake is to use pointers

你的错误是使用指针

std::vector<Student> students;

Student s;
while(theFile >> s.ID >> s.name >> s.surname >> s.points)
{
    students.push_back(s);
}

Now it will work.

现在它将起作用。

The problem was that you were reusing the same pointerover and over. So you end up with a vector of pointers all pointing at the same object. Which will have values for the last student read in.

问题是你一遍又一遍地重复使用相同的指针。所以你最终会得到一个指向同一个对象的指针向量。这将具有最后一个学生读入的值。

It seems a fairly common beginner trait to choose the complex alternative when the simpler one is correct so I would be interested to know why you chose to use pointers.

当更简单的选择是正确的时选择复杂的替代方案似乎是一个相当普遍的初学者特征,所以我很想知道您为什么选择使用指针。

回答by Kerrek SB

Here's how the code might look in modern C++:

下面是代码在现代 C++ 中的样子:

#include <string>
#include <istream>
#include <vector>

struct Student
{
    int ID;
    std::string name;
    std::string surname;
    int points;

    Student(int i, std::string n, std::string s, int p)
    : ID(i), name(std::move(n)), surname(std::move(s)), points(p) {}
};

std::vector<Student> read_students(std::istream & is)
{
    std::vector<Student> result;

    std::string name, surname;
    int id, points;

    while (is >> id >> name >> surname >> points)
    {
        result.emplace_back(id, name, surname, points);
    }

    return result;
}

Usage:

用法:

#include <fstream>
#include <iostream>

int main()
{
    std::ifstream infile("test.txt");
    auto students = read_students(infile);

    // ...
}

回答by Whizzil

Since you want to store pointers to Students but not Students in the vector.

因为您想在向量中存储指向学生的指针而不是学生。

Student* s = new Student();

while(theFile >> s->ID >> s->name >> s->surname >> s->points)
{
    students.push_back(s); // here I would like to add this struct s from a file
}

You have allocated only one Student and each time you loop you are reading to it again and again.

您只分配了一个学生,每次循环时,您都在一遍又一遍地阅读。

Instead you should allocate a new student on each loop and read in to the new allocated memory.

相反,您应该在每个循环中分配一个新学生并读入新分配的内存。

Student* s;
int tmpId, tmpPoints;
string tmpname, tmpsur;

while(theFile >> tmpId >> tmpname >> tmpsur >> tmpPoints)
{
    s = new Student();

    s->ID = tmpId ;
    s->name = tmpname;
    s->sur = tmpsur ;
    s->points= tmpPoints;

    studenti.push_back(s); // here You push a pointer to the newly allocated student
}
else
{
    // There is error reading data
}

Don't forget to delete each student when you don't need the vector anymore.

当您不再需要矢量时,不要忘记删除每个学生。

回答by 4pie0

your code doesn't work because you have one Student object and overwrite its members each time. Solution is to create a new Student object each time and pass a pointer to it to your vector:

您的代码不起作用,因为您有一个 Student 对象并且每次都覆盖其成员。解决方案是每次创建一个新的 Student 对象并将指向它的指针传递给您的向量:

std::vector<Student*> students;
int tmpId, tmpPoints;
string tmpname, tmpsur;

while(theFile >> tmpId >> tmpname >> tmpsur >> tmpPoints)
{
    Student* s = new Student();
    s->ID = tmpId ;
    s->name = tmpname;
    s->sur = tmpsur ;
    s->points= tmpPoints;

    students.push_back(s); // push a pointer to new student object
}
else
{
    // ...
}