Best wa to retrieve keys of a map

M

Marco Spatz

Hi,

I was wondering if there's an easy way to retrieve the key values of a
map (I think in Java this is possible by a member function).

I know that it is possible to iterate over the map and store the
iterators "first" member, but is there a way that needs less writing? (I
hate writing ;) )

Thanks in advance,
Marco
 
A

alcfse

sorry but no:

struct map_key: public
std::unary_function<std::pair<your_key_type,your_value_type>,your_key_type>{
your_key_type
operator()(std::pair<your_key_type,your_value_type>,element){
return element.first;
};
};

std::map<your_key_type,your_value_type> yourmap;
//...insert some elements

std::vector<your_key_type> keys_of_map;
keys_of_map.reserve(yourmap.size());
std::transform(yourmap.begin(),
yourmap.end(),std::back_inserter(keys_of_map),map_key());


you can spruce that up with some hot template action but you get the
idea.

Marco Spatz wrote:
 
R

Roland Pibinger

sorry but no:

struct map_key: public
std::unary_function<std::pair<your_key_type,your_value_type>,your_key_type>{
your_key_type
operator()(std::pair<your_key_type,your_value_type>,element){
return element.first;
};
};

std::map<your_key_type,your_value_type> yourmap;
//...insert some elements

std::vector<your_key_type> keys_of_map;
keys_of_map.reserve(yourmap.size());
std::transform(yourmap.begin(),
yourmap.end(),std::back_inserter(keys_of_map),map_key());

Is that a contribution to the Obfuscated C++ contest?
you can spruce that up with some hot template action but you get the
idea.

Well, I guess I've got _your_ idea.
 
S

Selwyn Alcantara

whew, I'm glad someone got the joke ;)

to op: shorter answer: no, you can't do that. just fill a vector with
the keys as you suggested.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top