Necktwi
Necktwi

Reputation: 2617

how to get the pointer to a pair in std::map

I want to store a different order for the pairs in std::map<string,void*> by pushing the pointers to pairs in the map on to a vector<pair<string,void*>*> in a desired order. How to get the pointer to each pair in the map?

Upvotes: 2

Views: 7988

Answers (3)

Nandu
Nandu

Reputation: 808

std::map<string,void*> mymap;
std::map<string,void*>::iterator mapIter = mymap.begin();

mapIter is the iterator (which acts like pointer) to each pair, starting with first.

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106076

Just iterate over the map taking the address of elements:

for (auto& my_pair : my_map)
    my_vector.push_back(&my_pair);

Upvotes: 1

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

If you dereference an iterator of the map, you get a reference to the pair. Taking the address of that gives you a pointer to the pair.

auto it = map.begin();
auto ptr = &*it;

Use care when declaring the pair, though, as the first element is const: pair<const string, void *>. Or use std::map<string,void*>::value_type instead of pair.

Upvotes: 3

Related Questions