Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the type specifier given an object

I am trying to write a template function that will take an STL container and will display all the occurrences of the elements in it and the number that they have occurred. I am planning to use a map, iterate through the container and either add a new element if it does not exist or increment the count of occurrences for the element.

Declaration:

template < typename Container_t >
void findOccurrences (const Container_t& inContainer);

My question is: can I somehow get the type specifier of the element that the container holds? So when I create my map the key value would be the element in the inContainer. Something like :

map < typeid ( * inContainer.begin()), int > occurrences;

Or would I have to change my template to something like this:

template < typename Container_t , typename Element_t >
void findOccurrences ( const Container_t & inContainer , Element_t dummy )
{
  map < Element_t , int > occurrences;
}

Thanks

like image 462
Nickolay Kondratyev Avatar asked Jun 26 '11 19:06

Nickolay Kondratyev


3 Answers

How about something like this:

#include <map>
#include <iterator>

template <typename Iter>
void histogram(Iter begin, Iter end)
{
  typedef typename std::iterator_traits<Iter>::value_type T;

  std::map<T, size_t> h;

  while (begin != end) ++h[*begin++];

  // now h holds the count of each distinct element
}

Usage:

std::vector<std::string> v = get_strings();
histogram(v.begin(), v.end());
like image 156
Kerrek SB Avatar answered Sep 24 '22 08:09

Kerrek SB


You want typename Container_t::element_type

That is,

std::map <typename Container_t::element_type, int>
like image 22
Armen Tsirunyan Avatar answered Sep 22 '22 08:09

Armen Tsirunyan


With C++0x, it's really easy:

map<decltype(*c.begin()), int> occurrences;

With C++03, you probably need to use a typedef from the container:

template<typename Container>
// ...
map<Container::element_type, int> occurrences;
like image 31
Ben Voigt Avatar answered Sep 24 '22 08:09

Ben Voigt