iterator for map - problem with searching
hello i got an iterator running on a multimap ,my multimap includes two fields the first 1 is the key value which is a string Lastname and the second 1 is the data which is a pointer to an object called Employee. in my program i need to be able to find an element inside my map using iterator (cause i am trying to find the data by its ID and not by the key value). i want to have some sort of indicator that will tell me if the element i am looking for is inside my map or not. thanks in advance. and this is my Find code :
MultiMap::iterator iterator;
iterator=m_municipalityMap.begin();
bool flag = false;
while(!(flag) && iterator != m_municipalityMap.end())
{
if(strcmp(iterator->second->GetId() , id) == 0)
{
flag=true;
break;
}
iterator++;
}
if (flag==false)
cout << "could not find Employee"<<endl;
return iterator;
what i need to know if there is a way to know if the iterator stands on no开发者_如何学编程thing like comparing to NULL on pointers
You could use the std::find_if algorithm with a suitable predicate that will handle finding your Employee based on the ID.
This is an adaption of an example found in "The C++ Standard Library - A Tutorial and Reference" by Nicolai M. Josuttis, Addison-Wesley, 1999:
class value_id_equals
{
private:
string m_id;
public:
// constructor (initialize id to compare with)
value_id_equals (string id)
: m_id(id) { }
// comparison
bool operator() (pair<string, Employee*> elem)
{
return (!strcmp(elem.second->GetID(), m_id.c_str()));
}
};
...
pos = find_if(your_map.begin(),your_map.end(), // linear complexity
value_id_equals(theID));
If you need two keys in the container you could try Boost Multi-index Container.
Another solution is to create two maps, each one with own key, and keep your data in each by (smart) pointers.
精彩评论