0

I have two classes, namely Players and Team In the Team class, I have array of Players instances, and the MAX_SİZE = 11

#define MAX 11
class Players{
// Some private and public members 
};
class Team {
private:
    Players players[MAX];
// Some other private and public members
};

I want to implement the addNewPlayer method in my Team class. Whenever I call this method, I should be able to the add the name of the player to the end of this Players instances array, which is players. Now the function I consider is like :

void Team :: addNewPlayer(Players new_player){
       // add new_player to the end of the array
       }

I know the Stacks and Queues data structures as well. However, there is a restriction on using arrays only.
Is there any efficient way of adding new object to the array of objects in other class in general?

7
  • players[currentNumberOfPlayers] = new_player? Commented Nov 18, 2021 at 19:50
  • Players players[MAX]; You can't change the size of that - it's fixed at MAX. Commented Nov 18, 2021 at 19:51
  • 1
    In C++, arrays don't have a concept of "add to the end". If an array holds 11 Players, that size cannot change. It will always and only hold 11 Players. Commented Nov 18, 2021 at 19:51
  • @Johnny Mopp. Yes the size is fixed by 11, which is an upper bound. I can add at most 11 players to the team. What is wrong with this if the team is initally empty? Commented Nov 18, 2021 at 19:54
  • 2
    Don't. Replace array with std::vector and use std::vector::push_back(). Commented Nov 18, 2021 at 19:55

2 Answers 2

1

 players array is defined within Team class. To assign it a size; you use the variable MAX, if this variable uses an appropriate value, suppose one different from its maximum capacity that depends on the hardware, you can try creating a new array replacing the one of the class with a new length and element:

void Team::addNewPlayer(Players new_player) {

    // add new_player to the end of the array
    int newSize = sizeof(players)/sizeof(players[0]);
    Players newArray[newSize+1];
    
    for (int i=0; i < newSize; i++) {
        newArray[i] = players[i];
    }

    newArray[newSize] = new_player;
    players = newArray;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You'll need the current count of players in your team. Then you'll want to add a new_player to the players[currentcount]

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.