1

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;
    }
martinthenext
  • 1,308
  • 1
  • 15
  • 28

2 Answers2

1

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
  • 52,325
  • 13
  • 128
  • 140
  • Yup, I would even suggest using `map::iterator` – orip Nov 28 '09 at 20:30
  • 2
    Yeah, it would be easier to just return a map iterator, rather than wrapping the map iterator in your own iterator class. – Charles Salvia Nov 28 '09 at 20:33
  • 1. your note about value type is absolutely right, thank you 2. i have a map of pair inside to search OntologyClass objects. i needed an iterator with * and -> operators returning OntologyClass objects (pointers), so i've wrapped standard map::iterator. That is why i have it as a member variable. – martinthenext Nov 28 '09 at 20:34
  • i've added implementation of the dereference operator to the body of the post – martinthenext Nov 28 '09 at 21:08
  • martinthenext, since your iterator is returning `OntologyClass&` from `operator*`, its value type is `OntologyClass`, not a pointer to it. – avakar Nov 28 '09 at 22:28
0

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

This stack overflow answer has a decent example on how to do that: iterator adapter to iterate just the values in a map?

Community
  • 1
  • 1
Eld
  • 974
  • 6
  • 9