我想创建一个模板方法,用于独立于元素类型添加和计算 map (STL) 中的元素。问题是:我可以使用迭代器类型的模板,如下所示吗?
template < typename Type, typename Iter >
void TextStat::addElement(Type element, map<Type, int> map, Iter &it) {
it = map.find(element);
if ( it == map.end() ) {
map.insert(pair<Type, int>(element, 1));
} else {
it->second += 1;
}
}
最佳答案
你可以这样写你的方法:
template <typename Type>
void TextStat::addElement(const Type& element, std::map<Type, int>& m) {
std::map<Type, int>::iterator it = m.find(element);
if (it == m.end()) {
m.insert(std::pair<Type, int>(element, 1));
} else {
it->second += 1;
}
}
或者更简单,因为 int
的默认值初始化是 0
:
template <typename Type>
void TextStat::addElement(const Type& element, std::map<Type, int>& m) {
m[element]++;
}
关于c++ - 迭代器类型的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22042341/