tags:

views:

70

answers:

2

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

+3  A: 

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!

rlbond
thanks thats what i was looking for.
Sriram
The return type should be `mymap::size_type`, not `size_t`.
AndreyT
You're partially correct, AndreyT, however `mymap` is not a type.
rlbond
A: 

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.

Nikolai N Fetissov