Is there a Java Map keySet() equivalent for C++'s std::map
?
The Java keySet()
method returns "a set view of the keys contained in this map."
Is there a Java Map keySet() equivalent for C++'s std::map
?
The Java keySet()
method returns "a set view of the keys contained in this map."
All of the answers presented thus far end up creating a
std::set
directly, which may not be ideal: if you only want to be able to iterate over the keys, you don't want to have the overhead of creating a whole new container.A more flexible option would be to use a transform iterator that converts a
std::map
iterator into some type of iterator that just yields the key when dereferenced. This is rather straightforward using the Boost Transform Iterator:With these utility functions, you can convert any range of
std::map
iterators (or iterators into any other pair associative container you may have) into a range of just the keys. As an example:This program outputs:
If you really do want a
std::set
containing the keys, you can easily create one using these iterators:Overall, it's a more flexible solution.
If you don't have Boost or don't want to use Boost or can't use Boost, this specific transform iterator can be implemented quite easily:
The usage for this is the same as for the Boost version.
Boost.Range provides this as boost::adaptors::map_values:
Perhaps the following might be of use:
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:
Here is a one-and-a-bit liner:
If you don't have
select1st
:you can implement it yourself: