views:

281

answers:

2

std::map.find() is intended to return an map::iterator to an element it found if there is some or to the end() if not. I get BadPtr returned to me. The exactly same construct works fine in the other part of code. What is this?

class OntologyContainer {
    map<string, OntologyClass*> data;
    OntologyClass* last_added;
public:
    class iterator : public std::iterator<bidirectional_iterator_tag, OntologyClass> {
     map<string, OntologyClass*>::iterator itr;
    public:
     iterator(map<string, OntologyClass*>::iterator it) : itr(it) { }

    ...
    }

    iterator begin() {
     return iterator(data.begin());
    }

    iterator end() {
     return iterator(data.end());
    }

    iterator Find(const string & to_find) {
     map<string, OntologyClass*>::iterator it = data.find(to_find);
     // this is where it fails
     return iterator(it);
    }

map::iterator is wrapped for the sake of making operators * and -> returning OntologyClass objects and pointers respectively:

            OntologyClass& operator* () {
  return *(itr->second);
 }

 OntologyClass* operator->() {
  return itr->second;
 }
+1  A: 

It might be something to do with the fact that you inherit from std::iterator<bidirectional_iterator_tag, OntologyClass>, making your iterator value_type to be OntologyClass, rather than a pointer to OntologyClass, which is what your map iterator uses. How are you implementing the dereference operator?

Charles Salvia
Yup, I would even suggest using `map<string, OntologyClass*>::iterator`
orip
Yeah, it would be easier to just return a map iterator, rather than wrapping the map iterator in your own iterator class.
Charles Salvia
1. your note about value type is absolutely right, thank you2. i have a map of <string, OntologyClass*> pair inside to search OntologyClass objects. i needed an iterator with * and -> operators returning OntologyClass objects (pointers), so i've wrapped standard map<string, OntologyClass*>::iterator. That is why i have it as a member variable.
martinthenext
i've added implementation of the dereference operator to the body of the post
martinthenext
avakar
thanks avakar, that was a wrong edit indeed
martinthenext
+1  A: 

if you can use boost I suggest using boost::transform_iterator.

This stack overflow answer has a decent example on how to do that: http://stackoverflow.com/questions/259240/iterator-adapter-to-iterate-just-the-values-in-a-map

Eld