Question

I try to read in some data of teams and players and change the data. The Player class members have pointers to the teams from the Team class, while the Teams have a playerlist filled with pointers to the players.

The problem comes with the readin()-function which reads in the team and player data from a txt.file and returns a vector of teams. After the readin-process the pointers created in the readin-process seem to direct to wrong addresses.

So reading out data from the vector of teams returned by the read-in function is not the same anymore than reading out the data from the pointers created in the read-in function.

Here is the general structur of the classes:

#include <iostream>
#include <vector>
#include <string>

class Player;
class Team
{
public:
    std::vector<Player*> getplayerlist(){
        return playerlist;
    }
    void setteamname(std::string x){
        teamname = x;
    }
    std::string getteamname(){
        return teamname;
    }
    void Team::addPlayer(Player* x){
        playerlist.emplace_back(x);
    };



private:
    std::vector<Player*> playerlist;
    std::string teamname;

};

class Player
{
public:
    Team* getpteam(){
        return pteam;
    }
    void setpteam(Team* x){
        pteam = x;
    }
    void setinformation(std::string x, int y){
        name= x;
        id = y;
      }

private: 
    int id;
    std::string name;
    Team* pteam;
};

And here is the structure of the read-in function

vector<Team> readin(){

//some readin stuff

//if the line contains the teamname

Team team;
team.setteamID_(a);
team.setteamname_(word2);
Teamvector.emplace_back(team);

//if the line contains player data
//add the player to the team created before     

Player* player = new Player();
player->setinformation_(b, word1, lname, str, &Teamvector[a-1]);
Teamvector[a-1].addPlayer(player);

return Teamvector;
}

But if i compare the addresses of &Teamvektor[0] and

vector <Team> team = readin();
&team[0] 

they are different. How can i "remain" the adress of the stored teams ?

Was it helpful?

Solution

You are returning std::vector by value: this means container is being copied, thus elements have same values but different addresses in memory.

There are few ways how to handle this. For example:

  1. Create container and fill it in your method:

    std::vector<Team>   v;
    
    void readin_fillVector( vector<Team>& v) {
      //..  v.push_back( team);
    }
    
  2. Pass iterator

    void readin_fillVector( std::back_insert_iterator< std::vector<Team> > it) {
      //..  (*it)++ = team;
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top