Есть ли набор ключей Карты Java () эквивалентен для C++ 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;
}
Перегрузка для функции make_key_set , принимающей STL-совместимые последовательности, такие как std :: vector, std :: deque или std :: list могут иметь следующий вид:
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);
}
}
Вот однозначный лайнер:
map<K,V> m;
...
// Useful stuff goes here
...
set<K> s;
transform(m.begin(), m.end(), inserter(s, s.begin()), select1st<pair<K,V> >());
Если у вас нет select1st
:
template <class P>
struct select1st : public std::unary_function<P, typename P::first_type>
{
const typename P::first_type& operator()(const P &arg) const { return arg.first; }
};
вы можете реализовать это сами:
vector<T> keys;
for (map<T,S>::iterator it=m.begin(); it!=m.end; it++)
keys.push_back(it->first)