结构向量push_back C ++

时间:2015-02-21 05:28:05

标签: c++ vector struct push-back

我在弄清楚如何使用push_back函数将结构的数组元素推入TeamV向量时遇到了问题。

这是我到目前为止的代码:

const int MEMBERS = 3;
const int TEAM_NUM = 4;

struct TeamS
{
   int ID_NUM;
   string team_members;
};


int main()
{
   int arrayS = 0;
   const int ID[TEAM_NUM] = { 123, 321, 456, 789 };
   const string TEAM [TEAM_NUM][MEMBERS] =
   {
      { "Sarah", "Joe", "John" }, 
      { "Chris", "Kevin", "James" }, 
      { "Tom", "Kim", "Emily" }, 
      { "Jill", "Jason", "Jim" }
   };
   vector <TeamS> TeamV;
   Initialize(TeamV, ID, TEAM, arrayS);

   return 0;
}



void Initialize(vector <TeamS> & TeamV, const int Id[], const string m[][MEMBERS], int arraysize)
{
   cout << "Starting initialization" << endl;
   for (arraysize; arraysize < TEAM_NUM; arraysize++)
   {
      TeamV.push_back(???)
         TeamV [arraysize].ID_NUM = Id[arraysize];
      TeamV [arraysize].team_members = m[arraysize][MEMBERS];

   }
   cout << "Ending initialization" << endl;
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

  • 首先,您需要更改TeamS以获得团队成员的string列表,而不仅仅是string

    struct TeamS
    {
       int ID_NUM;
       std::vector<string> team_members;
    };
    
  • 在初始化teamV的函数中:

    void Initialize(vector <TeamS> & TeamV, const int Id[], const string m[][MEMBERS], int arraysize)
    {
       cout << "Starting initialization" << endl;
       for (arraysize; arraysize < TEAM_NUM; arraysize++)
       {
          // Create an instance of TeamS and flesh out its contents.
          TeamS team;
          team.ID_NUM = Id[arraysize];
          for ( int i = 0; i < MEMBERS; ++i )
          {
             team.team_members.push_back(m[arraysize][i]);
          }
    
          // Now add the TeamS to TeamV.
          TeamV.push_back(team);
       }
       cout << "Ending initialization" << endl;
    }
    

    您可以采用稍微不同的方法,将空TeamS添加到TeamV,并充实TeamV中已有成员的内容。

    void Initialize(vector <TeamS> & TeamV, const int Id[], const string m[][MEMBERS], int arraysize)
    {
       cout << "Starting initialization" << endl;
       for (arraysize; arraysize < TEAM_NUM; arraysize++)
       {
          // Add an tempy TeamS to TeamV.
          TeamS team;
          TeamV.push_back(team);
    
          // Flesh out its contents of the element in TeamV.
          TeamV[arraysize].ID_NUM = Id[arraysize];
          for ( int i = 0; i < MEMBERS; ++i )
          {
             TeamV[arraysize].team_members.push_back(m[arraysize][i]);
          }
       }
       cout << "Ending initialization" << endl;
    }