【发布时间】:2012-06-29 11:35:17
【问题描述】:
我想出了以下代码,它演示了一种在 STL 集合上进行一般迭代并获得键值的技术,而不管键的存储方式如何。
上下文是我正在重构两个函数,它们都在两个集合上运行相同的功能:一个是 set<int>,另一个是 map<int, int>,所以在第一种情况下,我想对 @987654323 采取行动@ 并在第二个 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<int,int> 的专用案例更通用一点,因为无论键和值实际上是什么,这种方法显然都适用于 map。
任何指针(没有双关语)都会很有用。请注意,我不能使用 C++11 解决方案,尽管我对从学术角度使用它的解决方案感兴趣。谢谢。
【问题讨论】:
-
并非所有的集合都有 key_types,所以我不明白一般情况下如何做到这一点。
-
@juanchopanza:对不起,你是对的。我真正的意思是associative 集合。 generic,我的真正意思是“对于我的情况来说足够通用”:)