Random elements from linked list

Hello,
I have a linked list that holds data about people (name, age, gender, race, etc) and I need to be able to get two random elements(one male, one female) from the list. I really have no clue how I would do this because as far as I am aware you can't access a list by a certain element number like you can array. I'd have to traverse through it but that still doesn't help with pulling 2 random elements from it. I'm thinking maybe set a variable to count the number of male/female elements then traverse through the list a random number less than the variable? I'm honestly really confused on how I can do this. Thank you in advance.
You can implement an index into a list<A> functionally:
1
2
3
4
5
6
7
8
9
10
11
template <class T>
typename std::list<T>::const_iterator
list_index(const std::list<T>& l, std::size_t n)
{
  for (auto itr = l.cbegin(); itr != l.cend(); ++itr) {
    if (!n--) {
      return itr;
    }
  }
  throw std::out_of_range("index not found");
}
Topic archived. No new replies allowed.