I'm a C++ beginner (no prior programming experience). I'm writing a text-based game and I have a core module to develop for the "Population" of the game. So far I've established the population growth rates (based on pre-defined natality and mortality rates) and what I'm seeking to do now is to create a unique object for each citizen.
I've created the Citizen class, and I use a vector to generate the initial population of citizens:
vector<Citizen> myCitizens (100);
There is a function that sets several initial values for each of these 100 citizens. No problems there.
Every "year" the program calculates the births and deaths for that year. I want to add new objects to the myCitizens vector based on the number of births for that year.
I'm stuck on this function:
Declaration:
int new_citizens(int newBirths);
Definition:
int new_citizens(int newBirths)
{
myCitizens.push_back(newBirths);
}
Compiler build messages:
error: no matching function for call to 'std::vector<Citizen>::push_back(int&)'
note: candidate is:
note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = Citizen; _Alloc = std::allocator<Citizen>; std::vector<_Tp, _Alloc>::value_type = Citizen]
I've searched for the issue, looked at docs, messed around with changing the types to no avail. I've compiled examples where push_back did work. I think I'm missing a fundamental piece of the puzzle when it comes to creating class objects through a vector.
My current hypothesis at the time is that I'm declaring type information wrong or not correctly passing information to the vector. I'm going to keep trying. Any pointers in the right direction would be appreciated!
Thank you,
Optimae
this defines a
vector
namedmyCitizens
comprised of 100 objects ofCitizen
class, and each of them is initialized withCitizen()
. Then if I correctly get that what you want to do is to resize vector to contain total number ofnewBirths
ofCitizen
objects you can do it this way:you can also use
std::vector::resize
to achieve this:note: using
resize
the size of container is adjusted to be exactly what you specify in call to this function: container size will be reduced if current size is greater than what you specified in call toresize
or increased if current size is less thannewBirths
.if however you want to add this number of new items to an existing vector, then you can do it this way:
or again, using resize: