hayesti
hayesti

Reputation: 3073

Overload operator-> for STL iterator

I'm writing my own implementation of the C++ STL map container. Now I'm trying to implement the iterator. It should allow you to do something like iter->first and iter->second that returns the key/value respectively and where iter is an object not a pointer. I'm wondering how I should overload this? It's a bit confusing because I'm not sure what the return type should be; it has to be an object with members first/second I suppose. Is it typical to return a reference to a wrapper/interface object or something like that?

Upvotes: 1

Views: 3013

Answers (5)

UncleBens
UncleBens

Reputation: 41331

The value_type of a standard map is std::pair<const KeyType, MappedType>.

To achieve normal pointer semantics, operator* returns a reference, whereas operator-> returns a pointer.

//minimal example
#include <utility>
#include <cstdio>

struct It
{
  std::pair<const int, int> pair;
  std::pair<const int, int>* operator->() { return &pair; }
  std::pair<const int, int>& operator*() { return pair; }
};

int main()
{
  It it = {std::make_pair(10, 20) };
  (*it).second = 30;
  std::printf("%d %d\n", it->first, it->second);
}

Upvotes: 3

uckelman
uckelman

Reputation: 26234

std::map<K,V>::iterator iterates over objects of type std::pair<K,V>.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477060

Yes, you'll need a proxy to hold the relevant reference.

As for the type: standard-library iterators typically dereference to something of type value_type. For map<K,V>, the value type is std::pair<K, V> (or rather, pair<key_type, mapped_type>), which is where you get the first/second interface from.

(One of Stephan Lavavej's lectures explains how the MSVC++ implementation uses the same underlying data structure for set and map; the only difference is that set::value_type equals set::key_type, while map::value_type is pair<key_type, mapped_type>. That way you can tell the two apart with a simple trait check, but the iterator interface is virtually identical.)

Upvotes: 6

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

If you really mean the C++ standard library, then the value_type of a map is a pair. A pair has members first and second. Dereferencing an iterator in a map gives you a pair.

Upvotes: 6

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76808

The answer to your question is yes. You should return a proxy-object or a reference to a proxy-object to get that behavior.

Upvotes: 1

Related Questions