当前位置: 首页 > 面试题库 >

是否有Java Map keySet()等效于C ++的std :: map?

单于庆
2023-03-14
问题内容

是否有与C ++等效的Java Map keySet()std::map

Java
keySet()方法返回“此映射中包含的键的设置视图”。


问题答案:

也许以下可能有用:

#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, "\n"));

  return  0;
}

使用STL兼容序列(例如std :: vector,std :: deque或std :: list)的 make_key_set
函数的重载可以如下所示:

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中执行

  • 问题内容: 我知道我们可以使用Java中的方法通过指定其位置来获取字符串中的单个字符。C#中有等效的方法吗? 问题答案: 您可以像数组一样索引C#中的字符串,然后在该索引处获取字符。 例: 在Java中,您会说 在C#中,您会说

  • 问题内容: 在JavaScript中: C#应用程序是否等效?为了转义HTML字符,我使用了: 但是我不确定如何将匹配项转换为JS使用的正确十六进制格式。例如此代码: 返回“ 的,而不是它看起来像我需要了分割字符串为字节或东西。 编辑:这是一个Windows应用程序中,唯一可用的项目有:,,和。 问题答案: 或者是转义旨在成为URL一部分的字符串的正确方法。 以字符串为例: -> -> ->也编码

  • 本文向大家介绍C#是否等效于Java的Thread.setDaemon?,包括了C#是否等效于Java的Thread.setDaemon?的使用技巧和注意事项,需要的朋友参考一下 与Java的Thread.setDaemon等效的C#是前台线程和后台线程的概念。 当前台线程关闭时,后台线程将终止。前台线程继续运行,直到最后一个前台线程终止。 用于后台线程的属性是IsBackground,该属性获取

  • 问题内容: 我知道Java本身没有直接的等效项,但也许是第三方? 真的很方便。当前,我想实现一个迭代器,该迭代器生成树中的所有节点,这大约是带有yield的五行代码。 问题答案: 我知道的两个选项是2007年的Aviad Ben Dov的infomancers- collections库 和2008年的Jim Jimler的YieldAdapter库 (在另一个答案中也提到了)。 两者都允许您使用

  • 问题内容: 如何在Java中解码使用HttpServerUtility.UrlTokenEncode在C#中编码的字符串? 问题答案: 我尝试使用(ctor接受一个参数,说明编码/解码是否是url安全的),但事实证明它的实现方式与UrlTokenEncode / Decode不同。 我最终将C#实现迁移到Java: