C++ iterating a struct

后端 未结 4 1700
囚心锁ツ
囚心锁ツ 2021-01-21 10:27

Is it possible to iterate through a struct?

For example

struct team{
   int player1;
   int player2;
   int player3;
   int player4;
   ...
   int player         


        
4条回答
  •  抹茶落季
    2021-01-21 11:06

    To answer your question as you've asked it, I believe that you can use the pre-compiler macro Pack (the exact phrase depends on your compiler) to guarantee the structure of the memory used to create an instance of your struct. And then you technically could increment a pointer to move through it... if you're mad. That would be a very poor way to do and not at all guaranteed to work on different compilers or even different days of the week. No what you want is a data structure to do the job for you; they come with a 100% cash-back guarantee!

    The most basic structure to do this with is a fixed size array, e.g:

    struct team
    {
        int players[99]; //an array
        int manager;
        int coach;
        string teamName;
        //etc etc
    }
    

    Then to access your players

    team myTeam;
    for(int i(0); i < 99; ++i)
    {
        myTeam.players[i]; //do whatever
    }
    

    The limitation of an array is that you cannot change its size once it's created. So if you try

    myTeam.players[99]; //accessing invalid memory - the array values are 0 - 98
    

    More advanced

    If you need a data structure that can change size after it's created, e.g you might want to add a few more players to your team at some point in the future. Then you can use a dynamic data structure such as the std::vector or the std::deque or std::list

提交回复
热议问题