获取给定对象的类型说明符

Nic*_*yev 5 c++ templates types stl

我正在尝试编写一个模板函数,它将获取一个STL容器,并显示其中所有元素的出现次数以及它们发生的次数.我打算使用一个map,遍历容器并添加一个新元素(如果它不存在)或增加元素的出现次数.

宣言:

template < typename Container_t >
void findOccurrences (const Container_t& inContainer);
Run Code Online (Sandbox Code Playgroud)

我的问题是:我可以以某种方式获取容器所包含的元素的类型说明符吗?因此,当我创建我的地图时,键值将是该元素inContainer.就像是 :

map < typeid ( * inContainer.begin()), int > occurrences;
Run Code Online (Sandbox Code Playgroud)

或者我是否必须将模板更改为以下内容:

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

谢谢

Ker*_* SB 4

像这样的事情怎么样:

#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
}
Run Code Online (Sandbox Code Playgroud)

用法:

std::vector<std::string> v = get_strings();
histogram(v.begin(), v.end());
Run Code Online (Sandbox Code Playgroud)