Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 复制向量并保留成员的内存地址_C++_Pointers_Vector_Stl_Pass By Value - Fatal编程技术网

C++ 复制向量并保留成员的内存地址

C++ 复制向量并保留成员的内存地址,c++,pointers,vector,stl,pass-by-value,C++,Pointers,Vector,Stl,Pass By Value,我试着读入一些球队和球员的数据,然后改变数据。 玩家类成员有来自团队类的指向团队的指针,而团队有一个装满指向玩家指针的玩家列表 这个问题来自readin()-函数,它从txt.file中读取球队和球员数据,并返回球队向量。在readin进程之后,readin进程中创建的指针似乎指向错误的地址 因此,从read-in函数返回的团队向量中读取数据与从read-in函数中创建的指针中读取数据不同 以下是这些类的一般结构: #include <iostream> #include <v

我试着读入一些球队和球员的数据,然后改变数据。 玩家类成员有来自团队类的指向团队的指针,而团队有一个装满指向玩家指针的玩家列表

这个问题来自readin()-函数,它从txt.file中读取球队和球员数据,并返回球队向量。在readin进程之后,readin进程中创建的指针似乎指向错误的地址

因此,从read-in函数返回的团队向量中读取数据与从read-in函数中创建的指针中读取数据不同

以下是这些类的一般结构:

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

他们是不同的。我如何“保留”存储团队的地址?

您正在按值返回
std::vector
:这意味着正在复制容器,因此元素在内存中具有相同的值但不同的地址

有几种方法可以解决这个问题。例如:

  • 创建容器并将其填充到您的方法中:

    std::vector<Team>   v;
    
    void readin_fillVector( vector<Team>& v) {
      //..  v.push_back( team);
    }
    
    std::vector v;
    void readin_fillVector(vector&v){
    //…v.推回(团队);
    }
    
  • 传递迭代器

    void readin_fillVector( std::back_insert_iterator< std::vector<Team> > it) {
      //..  (*it)++ = team;
    }
    
    void readin\u fillVector(std::back\u insert\u迭代器it){
    //..(*it)++=团队;
    }
    

  • 我猜这就是问题所在,但不知道怎么解决这个问题。尝试返回一个向量,但失败了,我做了更改,但现在出现错误C2664:“Team::Team(const Team&”):无法将参数1从“Team”转换为“const Team&”\xmemory0它来自我计算出的行v.emplace\u back(Team)。编辑:我解决了这个问题,在我的测试中我的团队变成了另一个团队。Thx现在它的工作原理应该是请创建一个带有新代码和描述的新问题,以防出现新问题
    std::vector<Team>   v;
    
    void readin_fillVector( vector<Team>& v) {
      //..  v.push_back( team);
    }
    
    void readin_fillVector( std::back_insert_iterator< std::vector<Team> > it) {
      //..  (*it)++ = team;
    }