2014-02-26 11 views
1

요소 유형과 독립적으로 맵 (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; 
    } 
} 
+2

및 실행 그리고 무슨 일이 일어나는 지 알아보십시오 – deeiip

+0

지도의 복사본과 요소 사본을 가지고 작업 중입니다. – odedsh

+1

이 작업을 수행하는 방법은 간단합니다. 'theMap [theKey] ++;' – juanchopanza

답변

0

이 같이 당신의 방법을 쓸 수 있습니다 :

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]++; 
}