2

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?

10
  • 1
    Consider storing iterators in the vector, i.e. use std::vector<std::map<string,void*>::iterator> or maybe even std::vector<std::map<string,void*>::const_iterator> if applicable. Commented Oct 19, 2015 at 7:56
  • yeah @MatthausBrandl iterator is just 4bytes same as pointer. thank you Commented Oct 20, 2015 at 5:27
  • @MatthausBrandl are you sure that iterator don't have any heap memory? because iterator can point us to next and previous pairs! Commented Oct 20, 2015 at 5:33
  • This is not about size, it's about additional safety. If you're using a checked STL implementation (like Dinkumware's which is licensed by MS) you'll get an assertion if you're using invalid iterators. This is not the case for raw pointers. Commented Oct 20, 2015 at 16:17
  • I don't understand your question. Whatever they are internally (most likely raw pointers to tree nodes) is nothing you should depend on. And iterators do not point to next and previous elements but they know how to find them. Commented Oct 20, 2015 at 16:23

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

auto ptr = &*it; dont need this
I knew this is how it can be done but I got some other error which i miss took to it. Thanks for confirming.
1

Just iterate over the map taking the address of elements:

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

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.