Iterate keys in a C++ map

C++Stl

C++ Problem Overview


Is there a way to iterate over the keys, not the pairs of a C++ map?

C++ Solutions


Solution 1 - C++

map is associative container. Hence, iterator is a pair of key,val. IF you need only keys, you can ignore the value part from the pair.

for(std::map<Key,Val>::iterator iter = myMap.begin(); iter != myMap.end(); ++iter)
{
Key k =  iter->first;
//ignore value
//Value v = iter->second;
}

EDIT:: In case you want to expose only the keys to outside then you can convert the map to vector or keys and expose.

Solution 2 - C++

With C++11 the iteration syntax is simple. You still iterate over pairs, but accessing just the key is easy.

#include <iostream>
#include <map>

int main()
{
    std::map<std::string, int> myMap;

    myMap["one"] = 1;
    myMap["two"] = 2;
    myMap["three"] = 3;

    for ( const auto &myPair : myMap ) {
        std::cout << myPair.first << "\n";
    }
}

Solution 3 - C++

If you really need to hide the value that the "real" iterator returns (for example because you want to use your key-iterator with standard algorithms, so that they operate on the keys instead of the pairs), then take a look at Boost's http://www.boost.org/doc/libs/1_40_0/libs/iterator/doc/transform_iterator.html">transform_iterator</a>;.

[Tip: when looking at Boost documentation for a new class, read the "examples" at the end first. You then have a sporting chance of figuring out what on earth the rest of it is talking about :-)]

Solution 4 - C++

With C++17 you can use a structured binding inside a range-based for loop (adapting John H.'s answer accordingly):

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> myMap;

    myMap["one"] = 1;
    myMap["two"] = 2;
    myMap["three"] = 3;

    for ( const auto &[key, value]: myMap ) {
        std::cout << key << '\n';
    }
}

Unfortunately the C++17 standard requires you to declare the value variable, even though you're not using it (std::ignore as one would use for std::tie(..) does not work, see this discussion).

Some compilers may therefore warn you about the unused value variable! Compile-time warnings regarding unused variables are a no-go for any production code in my mind. So, this may not be applicable for certain compiler versions.

Solution 5 - C++

Without Boost

You can do this by simply extending the STL iterator for that map. For example, a mapping of strings to ints:

#include <map>
typedef map<string, int> ScoreMap;
typedef ScoreMap::iterator ScoreMapIterator;

class key_iterator : public ScoreMapIterator
{
  public:
    key_iterator() : ScoreMapIterator() {};
    key_iterator(ScoreMapIterator s) : ScoreMapIterator(s) {};
    string* operator->() { return (string* const)&(ScoreMapIterator::operator->()->first); }
    string operator*() { return ScoreMapIterator::operator*().first; }
};

You could also perform this extension in a template, for a more general solution.

You use your iterator exactly like you would use a list iterator, except you're iterating over the map's begin() and end().

ScoreMap m;
m["jim"] = 1000;
m["sally"] = 2000;

for (key_iterator s = m.begin(); s != m.end(); ++s)
    printf("\n key %s", s->c_str());

Solution 6 - C++

Below the more general templated solution to which Ian referred...

#include <map>

template<typename Key, typename Value>
using Map = std::map<Key, Value>;

template<typename Key, typename Value>
using MapIterator = typename Map<Key, Value>::iterator;

template<typename Key, typename Value>
class MapKeyIterator : public MapIterator<Key, Value> {

public:

	MapKeyIterator ( ) : MapIterator<Key, Value> ( ) { };
	MapKeyIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };

	Key *operator -> ( ) { return ( Key * const ) &( MapIterator<Key, Value>::operator -> ( )->first ); }
	Key operator * ( ) { return MapIterator<Key, Value>::operator * ( ).first; }
};

template<typename Key, typename Value>
class MapValueIterator : public MapIterator<Key, Value> {

public:

	MapValueIterator ( ) : MapIterator<Key, Value> ( ) { };
	MapValueIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };

	Value *operator -> ( ) { return ( Value * const ) &( MapIterator<Key, Value>::operator -> ( )->second ); }
	Value operator * ( ) { return MapIterator<Key, Value>::operator * ( ).second; }
};

All credits go to Ian... Thanks Ian.

Solution 7 - C++

You are looking for map_keys, with it you can write things like

BOOST_FOREACH(const key_t key, the_map | boost::adaptors::map_keys)
{
  // do something with key
}

Solution 8 - C++

Without BOOST, directly using key and value

for(auto const& [key, value]: m_map)
    {
    std::cout<<" key="<<key;
    std::cout<<" value="<<value<<std::endl;
    }

Solution 9 - C++

Here's an example of how to do it using Boost's transform_iterator

#include <iostream>
#include <map>
#include <iterator>
#include "boost/iterator/transform_iterator.hpp"

using std::map;
typedef std::string Key;
typedef std::string Val;

map<Key,Val>::key_type get_key(map<Key,Val>::value_type aPair) {
  return aPair.first;
}

typedef map<Key,Val>::key_type (*get_key_t)(map<Key,Val>::value_type);
typedef map<Key,Val>::iterator map_iterator;
typedef boost::transform_iterator<get_key_t, map_iterator> mapkey_iterator;

int main() {
  map<Key,Val> m;
  m["a"]="A";
  m["b"]="B";
  m["c"]="C";

  // iterate over the map's (key,val) pairs as usual
  for(map_iterator i = m.begin(); i != m.end(); i++) {
    std::cout << i->first << " " << i->second << std::endl;
  }

  // iterate over the keys using the transformed iterators
  mapkey_iterator keybegin(m.begin(), get_key);
  mapkey_iterator keyend(m.end(), get_key);
  for(mapkey_iterator i = keybegin; i != keyend; i++) {
    std::cout << *i << std::endl;
  }
}

Solution 10 - C++

You want to do this?

std::map<type,type>::iterator iter = myMap.begin();
std::map<type,type>::iterator endIter = myMap.end();
for(; iter != endIter; ++iter)
{
   type key = iter->first;  
   .....
}

Solution 11 - C++

When no explicit begin and end is needed, ie for range-looping, the loop over keys (first example) or values (second example) can be obtained with

#include <boost/range/adaptors.hpp>

map<Key, Value> m;

for (auto k : boost::adaptors::keys(m))
  cout << k << endl;

for (auto v : boost::adaptors::values(m))
  cout << v << endl;

Solution 12 - C++

If you need an iterator that just returns the keys you need to wrap map's iterator in your own class that provides the desired interface. You can declare a new iterator class from scratch like here, of use existing helper constructs. This answer shows how to use Boost's transform_iterator to wrap the iterator in one that only returns the values/keys.

Solution 13 - C++

You could

  • create a custom iterator class, aggregating the std::map<K,V>::iterator
  • use std::transform of your map.begin() to map.end() with a boost::bind( &pair::second, _1 ) functor
  • just ignore the ->second member while iterating with a for loop.

Solution 14 - C++

This answer is like rodrigob's except without the BOOST_FOREACH. You can use c++'s range based for instead.

#include <map>
#include <boost/range/adaptor/map.hpp>
#include <iostream>

template <typename K, typename V>
void printKeys(std::map<K,V> map){
     for(auto key : map | boost::adaptors::map_keys){
          std::cout << key << std::endl;
     }
}

Solution 15 - C++

With C++20, we have access to the ranges library, which has a nifty solution for this: std::views::keys

#include <ranges>

//...

std::map<int, int> myMap = {{1,2},{3,4},{5,6}};
auto keys = std::views::keys(myMap);
for(auto key : keys) {
    std::cout << key << std::endl;
}

Try it out yourself: https://godbolt.org/z/heeWv4Gh6

Solution 16 - C++

Without Boost, you could do it like this. It would be nice if you could write a cast operator instead of getKeyIterator(), but I can't get it to compile.

#include <map>
#include <unordered_map>


template<typename K, typename V>
class key_iterator: public std::unordered_map<K,V>::iterator {

public:

	const K &operator*() const {
		return std::unordered_map<K,V>::iterator::operator*().first;
	}

	const K *operator->() const {
		return &(**this);
	}
};

template<typename K,typename V>
key_iterator<K,V> getKeyIterator(typename std::unordered_map<K,V>::iterator &it) {
	return *static_cast<key_iterator<K,V> *>(&it);
}

int _tmain(int argc, _TCHAR* argv[])
{
	std::unordered_map<std::string, std::string> myMap;
	myMap["one"]="A";
	myMap["two"]="B";
	myMap["three"]="C";
	key_iterator<std::string, std::string> &it=getKeyIterator<std::string,std::string>(myMap.begin());
	for (; it!=myMap.end(); ++it) {
		printf("%s\n",it->c_str());
	}
}

Solution 17 - C++

For posterity, and since I was trying to find a way to create a range, an alternative is to use [boost::adaptors::transform][1]

Here's a small example:

#include <boost/range/adaptor/transformed.hpp>
#include <iostream>
#include <map>

int main(int argc, const char* argv[])
{
  std::map<int, int> m;
  m[0]  = 1;
  m[2]  = 3;
  m[42] = 0;

  auto key_range =
    boost::adaptors::transform(
      m,
      [](std::map<int, int>::value_type const& t) 
      { return t.first; }
    ); 
  for (auto&& key : key_range)
    std::cout << key << ' ';
  std::cout << '\n';
  return 0;
}

If you want to iterate over the values, use t.second in the lambda.

[1]: http://www.boost.org/doc/libs/1_60_0/libs/range/doc/html/range/reference/adaptors/reference/transformed.html "boost::adaptors::transform"

Solution 18 - C++

Lots of good answers here, below is an approach using a couple of them which lets you write this:

void main()
{
    std::map<std::string, int> m { {"jim", 1000}, {"sally", 2000} };
	for (auto key : MapKeys(m))
		std::cout << key << std::endl;
}

If that's what you always wanted, then here is the code for MapKeys():

template <class MapType>
class MapKeyIterator {
public:
	class iterator {
	public:
		iterator(typename MapType::iterator it) : it(it) {}
		iterator operator++() { return ++it; }
		bool operator!=(const iterator & other) { return it != other.it; }
		typename MapType::key_type operator*() const { return it->first; }	// Return key part of map
	private:
		typename MapType::iterator it;
	};
private:
	MapType& map;
public:
	MapKeyIterator(MapType& m) : map(m) {}
	iterator begin() { return iterator(map.begin()); }
	iterator end() { return iterator(map.end()); }
};
template <class MapType>
MapKeyIterator<MapType> MapKeys(MapType& m)
{
	return MapKeyIterator<MapType>(m);
}

Solution 19 - C++

I've adopted Ian's answer to work with all map types and fixed returning a reference for operator*

template<typename T>
class MapKeyIterator : public T
{
public:
    MapKeyIterator() : T() {}
    MapKeyIterator(T iter) : T(iter) {}
    auto* operator->()
    {
        return &(T::operator->()->first);
    }
    auto& operator*()
    {
        return T::operator*().first;
    }
};

Solution 20 - C++

I know this doesn't answer your question, but one option you may want to look at is just having two vectors with the same index being "linked" information..

So in..

std::vector<std::string> vName;

std::vector<int> vNameCount;

if you want the count of names by name you just do your quick for loop over vName.size(), and when ya find it that is the index for vNameCount that you are looking for.

Sure this may not give ya all the functionality of the map, and depending may or may not be better, but it might be easier if ya don't know the keys, and shouldn't add too much processing.

Just remember when you add/delete from one you have to do it from the other or things will get crazy heh :P

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBogdan BalanView Question on Stackoverflow
Solution 1 - C++aJ.View Answer on Stackoverflow
Solution 2 - C++John H.View Answer on Stackoverflow
Solution 3 - C++Steve JessopView Answer on Stackoverflow
Solution 4 - C++ElmarView Answer on Stackoverflow
Solution 5 - C++IanView Answer on Stackoverflow
Solution 6 - C++degskiView Answer on Stackoverflow
Solution 7 - C++rodrigobView Answer on Stackoverflow
Solution 8 - C++JindřichView Answer on Stackoverflow
Solution 9 - C++algalView Answer on Stackoverflow
Solution 10 - C++NaveenView Answer on Stackoverflow
Solution 11 - C++Darko VebericView Answer on Stackoverflow
Solution 12 - C++sthView Answer on Stackoverflow
Solution 13 - C++xtoflView Answer on Stackoverflow
Solution 14 - C++user4608041View Answer on Stackoverflow
Solution 15 - C++iamkrootView Answer on Stackoverflow
Solution 16 - C++Jack HaughtonView Answer on Stackoverflow
Solution 17 - C++ipapadopView Answer on Stackoverflow
Solution 18 - C++Superfly JonView Answer on Stackoverflow
Solution 19 - C++Gabriel HuberView Answer on Stackoverflow
Solution 20 - C++John DoeView Answer on Stackoverflow