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
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());
You want typename Container_t::element_type
That is,
std::map <typename Container_t::element_type, int>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With