Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of structs: adding elements C++

Tags:

c++

struct

vector

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)?

like image 507
Whizzil Avatar asked Dec 02 '22 23:12

Whizzil


1 Answers

Here's how the code might look in modern 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);

    // ...
}
like image 149
Kerrek SB Avatar answered Dec 21 '22 17:12

Kerrek SB