Reputation: 155
I have just started with OO and I have a question about constructors. This would just create the same object "Team a" over and over with a different parameter i, correct?
for (int i = 1; i < n+1; i++) Team a (i); // construct teams
How can I create different "Teams", i.e. Team a, Team b ... Team h if I know how many teams there has to be? Can't the parameter i be the attribute and the name at the same time (Team 1, Team 2..)?
Thanks in advanced for any tip or help!
Pd: this is the constructor I'm using (if you need more code please write it in the comments):
public:
//constructors
Team(int n); // (this will set number to n and points, goals_scored, goals_lost to 0)
Upvotes: 0
Views: 3138
Reputation: 48605
You can use a std::vector:
std::vector<Team> teams;
for(int i = 0; i < n; ++i)
teams.emplace_back(i + 1); // makes Team(i + 1) in vector
Note: the std::vector
uses zero based indexing so your team #1 is index 0:
teams[0]; // team #1
teams[1]; // team #2
teams[n]; // team #n + 1
Upvotes: 3
Reputation: 962
You would like to use map
from STL:
std::map <string, Team> Teams;
for (int i = 1; i < n+1; i++)
{
std::string noStr = std::to_string(i);
std::string teamName = "Team " + noStr; // "Team 1", "Team 2", ..., "Team N"
Teams[teamName] = Team(i); // Store Team object in the map
}
Now you can access any team using its name :
// For team 5 object
Teams["Team 5"]
Upvotes: 1
Reputation: 563
1st question: yes it would produce n times a variable a
of type Team
. But(!) It is local to the for loop at each iteration. You wont be able to use them later.
2nd question: pure numbers cant be names. This does not work:
int 1 = 1; // not(!) valid
You can use something like this:
int a_1 = 1 ;
int a_2 = 2;
But you can't produce this by a variable:
for (int i = 1; i < n+1; i++){
int a_i = 1; // defines a local variable "a_i"
int i = i ;// not valid i is already defined
}
You should use a container (e.g. a vector) of teams.
Upvotes: 0