是否有与 C++ 的 std::map 等效的 Java Map keySet()? [英] Is there a Java Map keySet() equivalent for C++'s std::map?
本文介绍了是否有与 C++ 的 std::map 等效的 Java Map keySet()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有与 C++ 的 std::map
等效的 Java Map keySet()?
Is there a Java Map keySet() equivalent for C++'s std::map
?
Java keySet()
方法返回 "此映射中包含的键的集合视图."
The Java keySet()
method returns "a set view of the keys contained in this map."
推荐答案
也许以下可能有用:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <map>
#include <set>
#include <string>
template< class Key,
class T,
class Comparator,
class MapAllocator,
class SetAllocator>
void make_key_set(const std::map<Key,T,Comparator,MapAllocator>& map,
std::set<Key,Comparator,SetAllocator>& set)
{
set.clear();
typedef typename std::map<Key,T,Comparator,MapAllocator> map_type;
typename map_type::const_iterator itr = map.begin();
while (map.end() != itr)
{
set.insert((itr++)->first);
}
}
int main()
{
std::map<std::string, double> m;
m["one"] = 1.1;
m["two"] = 2.2;
m["three"] = 3.3;
std::set<std::string> key_set;
make_key_set(m,key_set);
std::copy(key_set.begin(), key_set.end(),
std::ostream_iterator<std::string>(std::cout, "
"));
return 0;
}
采用 STL 兼容序列(例如 std::vector、std::deque 或 std::list)的 make_key_set 函数的重载可以如下所示:>
An overload for the make_key_set function taking STL compatible sequences such as std::vector, std::deque or std::list can be as follows:
template< class Key,
class T,
class Comparator,
class MapAllocator,
class SeqAllocator,
template<class,class> class Sequence>
void make_key_set(const std::map<Key,T,Comparator,MapAllocator>& map,
Sequence<Key,SeqAllocator>& sequence)
{
sequence.clear();
typedef typename std::map<Key,T,Comparator,MapAllocator> map_type;
typename map_type::const_iterator itr = map.begin();
while (map.end() != itr)
{
sequence.push_back((itr++)->first);
}
}
这篇关于是否有与 C++ 的 std::map 等效的 Java Map keySet()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文