Using vector.size() in a function?

Hi -

I am playing with a little program where I create a virtual population. So far, I've used vectors to assign the sex randomly. (vector[i] = randomsex); What I'd like to do now is count the total of my population by counting the combined of both sexes. I know I can do this using: vector.size() but I'd like to somehow do this in a function called population that returns the number so I can just call population().

Unfortunately, this doesn't work as the vector is not carried over into the function, so I'm not sure what I need to do next. Is this the kind of thing I should be doing as a class? If so, how would I achieve that?

Thanks!
Last edited on
You will probably want to be doing it as classes. If you just want to get your code working you can pass the vector by reference.

What I would do is make a class to represent each person that contains their gender and name, age, etc. and then another class to contain a population, which just maintains an internal vector. Try using proper encapsulation (private member variables and public member functions) and such.

Here's another handy tip: use typedefs for your vector types to make your life easier:
1
2
3
4
5
6
7
8
9
10
typedef std::vector<Person> People_t; //People_t is the same as std::vector<Person>

People_t people; //is a vector of people

for(People_t::iterator it = people.begin(); it != people.end(); ++it)
{
    //iterates each person
}

People_t::size_t population_size = people.size(); //number of people 
Last edited on
Topic archived. No new replies allowed.