c++ - 迭代器类型的模板

标签 c++ templates stl iterator

我想创建一个模板方法,用于独立于元素类型添加和计算 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/

相关文章:

html - 启动一个 node.js 项目

用于扩展任意标准符合分配器的 C++ 设计模式

c++ - 从 Fortran 例程调用多线程 (openmp) c++ 例程

C++:std::sort 使用已销毁的对象和自定义谓词进行排序?

c++ - 为什么模板类会有未使用的类型?

c++ - C++11 标准中的哪条规则描述了下面提到的匹配?

c++ - 在 O(logn) 时间内使用 STL 堆实现 Decrease Key

c++ - RAII、伯克利套接字和 STL 容器

c++ - 否定 remove_if 中的谓词

c++ - 如何使用任务在 Visual Studio Code 中运行 Cmake