How do I get the first 5 elements of a map?

template<typename T, typename U>
void print_first_five( map<T,U> m )
  {
  for (int i = 0; i < (m.size() >= 5) ? 5 : m.size(); i++)
    cout << m[i].second;
  }

Hope this helps.

how do you do it with multimaps?

template<typename T, typename U>
void print_first_five( map<T,U> m )
  {
  for (int i = 0; i < (m.size() >= 5) ? 5 : m.size(); i++)
    cout << m[i].second;
  }

Hope this helps.

Argh.

Use an iterator.

template<typename A, typename B>
void print_5( const multimap<A, B>& m )
  {
  multimap<A, B>::const_iterator i;
  for (
    int n = 0, i = m.begin();
    (n < 5) and (i != m.end());
    n++, i++
    ) {
    cout << i->second << endl;
    }
  }
template<typename T, typename U>
void print_first_five( map<T,U> m )
  {
  for (int i = 0; i < (m.size() >= 5) ? 5 : m.size(); i++)
    cout << m[i].second;
  }

Hope this helps.

This is wrong, by the way. "m" looks up "i" as a key in the map. So it will not only fail to compile when "T" is not "int"; but even when it is an int, the binding might not exist.

Woops. Brain-farts strike me again. :X

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.