Reputation: 1190
i have a std::map and i am using iterator to find a certain key,value pair. After finding it i am unable to get the position of the key,value pair from the iterator. By doing another find i can get it, but i want a work around for this.
//mycode is this
std::map<std::string,myclass*> mymap;
size_t myfind(const std::string &s)
{
std::map<std:string,myclass*>::iterator i=mymap.find(s);
if((i==mymap.end())||((*i).second==0))
{
std::cout<<"some error\n";
}
else
{
//here i need to return the size_t value of the iterator i
}
}
NOTE: edited size_t as the position of key,value pair
Upvotes: 0
Views: 631
Reputation: 84159
What does size_t
have to do with anything? You found the key-value pair, key is a string, value is a pointer to some class. That's it. What size_t
value did you have in mind?
Some background to put you onto right track: map and set in STL are usually implemented as balanced binary tree (red-black tree.) Each node in the tree has the value (just key for set, or pair for map,) and two of pointers to child nodes. You can think of map::iterator
as a pointer to a node with fancy overloaded operators so, say, incrementing the iterator value moves the pointer to the next node in sort order. So there's no "size_t
value of the iterator". It's an instance of a class that wraps a pointer to binary tree node.
Upvotes: 0
Reputation: 67749
If you want to return the "position" of the result:
#include <iterator>
// ...
std::map<std::string,myclass*> mymap;
size_t myfind(const std::string &s)
{
std::map<std:string,myclass*>::iterator i=mymap.find(s);
if((i==mymap.end())||((*i).second==0))
{
std::cout<<"some error\n";
}
else
{
return std::distance(mymap.begin(), i);
}
}
However, you are probably better off just returning the iterator!
Upvotes: 3