user1393608
user1393608

Reputation: 1349

What is efficient way of transforming map's keyset into vector of keys

What is efficient way of transforming map's keyset into vector of keys currently i am iterating over my map and adding iter.first into vector, is this similar to Java's KeySet api?

Upvotes: 1

Views: 141

Answers (2)

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247899

One way to do it would be something like this:

std::vector<KeyType> v;
std::map<KeyType, ValueType> m;

v.reserve(m.size());
std::transform(m.begin(), m.end(), std::back_inserter(v), [](const std::pair<KeyType, ValueType>& p) { return p.first; });

Upvotes: 5

pmr
pmr

Reputation: 59811

If you are already using boost, the Range library comes with a convenient map_keys function, which takes away the need of a temporary vector.

A more general approach is putting some kind of transform_iterator on top of the map iterators (which is essentially what Boost.Range does).

Otherwise your approach of copying into a vector can be rewritten in terms of a std::transform call. Possibly preceded by vector::reserve to cut down on allocations.

If you don't have a transform iterator already, you probably want to use the last solution as the first two are rather hard to get right depending on how compatible with older standards you want to be.

Upvotes: 3

Related Questions