STL 컬렉션을 통해 일반적으로 반복하고 키 저장 방법에 관계없이 키 값을 얻기위한 기술을 보여주는 다음 코드를 작성했습니다. 하나는 set<int>
이고 다른 I가 *it
에 작용하고자하는 첫 번째 경우와 초이므로 map<int, int>
이다C++ STL 컬렉션에서 일반 key_type 얻기
이 컨텍스트는 I 둘 개의 모음에 동일한 기능을 제공 두 함수 리팩토링 오전이며 it->first
에 (it
이 const_iterator를합니다.) 중요한 것은
, 나는 컬렉션이 상당히 크다고이기 때문에이 작업을 수행 할 수 나는 단순히 그래서 만 처리 할 수있는 map
에서 set
을 만들어야 할 싶지 않아 하나의 특정 유형.
#include <map>
#include <set>
#include <iostream>
using namespace std;
// General case for obtaining from, say, a set.
template< typename T >
const typename T::key_type getKey(const typename T::const_iterator& it)
{
return *it;
}
// Specific case for a map<int,int>
template<>
const map<int, int>::key_type getKey< map<int, int> >(const map<int, int>::const_iterator& it)
{
return it->first;
}
template< typename T >
void dumpOut(T& coll)
{
for (typename T::const_iterator it = coll.begin(); it != coll.end(); ++it)
{
const typename T::key_type& a = getKey<T>(it);
cout << a << endl;
}
}
int main()
{
set<int> s1;
s1.insert(10);
s1.insert(15);
s1.insert(20);
dumpOut< set<int> >(s1);
map<int, int> m1;
m1.insert(pair<int, int>(11, -1));
m1.insert(pair<int, int>(16, -1));
m1.insert(pair<int, int>(21, -1));
dumpOut< map<int, int> >(m1);
return 0;
}
내 질문은 : 그것은 접근이 명확 관계없이 키와 값이 실제로 무엇인지, 일반적으로 map
위해 일하는 것이기 때문에 좀 더 일반적인 map<int,int>
에 대한 전문적인 케이스를 만드는 것이 가능하다.
모든 포인터 (의도 한 장난 없음)가 유용합니다. 학술적 관점에서 사용하는 솔루션에 관심이 있지만 C++ 11 솔루션을 사용할 수 없습니다. 감사.
하지 않음 모든 컬렉션에는 key_types가 있으므로이 방법을 일반적으로 어떻게 수행 할 수 있는지 알지 못합니다. – juanchopanza
@ juanchopanza : 죄송합니다, 당신 말이 맞아요. 제가 진정으로 의미하는 바는 associative * collection이었습니다. * 제네릭 *으로, "제 경우에는 충분히 일반화"를 의미했습니다. :) –