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?
CodePudding user response:
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;
}
CodePudding user response:
You'll need the current count of players in your team. Then you'll want to add a new_player to the players[currentcount]