I am maintaining a container class with an interface similar to std::map
/std::unordered_map
.
The interface claims to store std::pair<const X,Y>
(i.e that's what value_type
is). Internally, however, the implementation stores a sorted array of std::pair<X,Y>
.
The current implementation uses reinterpret_cast
to implement the iterators. My question is, is there a better alternative?
Moving to storing an array of std::pair<const X,Y>
wouldn't be possible, as the implementation needs to copy elements around in the array to implement insertion and deletion. One of the ways it does this is using std::sort
.
Edit: Although I believe the reinterpret_cast
invokes undefined behavior (or implementation defined?) I have yet to come across a compiler where this doesn't work - Am I worrying about nothing?
Current implementation of iterator's dereference:
template <class K, class M>
std::pair<const K,M>& operator*() {
std::pair<K,M>& result = ...;
return *reinterpret_cast<std::pair<const K,M>*)(&result);
}