Search code examples
c++pointerstemplateskey-valuereinterpret-cast

Cast two pointers to a pointer of std::pair like struct


I have the following simple struct that resembles std::pair. I want to cast two pointers keys and Values to a pointer of the pair. How can I do this?

Thanks!

K* keys;
V* Values;
/*  
length of keys = length of Values
goal: operation(keys, Values) ---> pair*
*/
template <typename K, typename V, K EmptyKey = K(-1)> struct pair {
    K first;
    V second;
    static constexpr auto empty_key = EmptyKey;
    bool empty() { return first == empty_key; }
  };


Solution

  • You have to copy the keys and values into the pairs.

    template <typename K, typename V>
    pair<K, V>* KVToPairs(const K* k, const V* v, unsigned int length) {
        if (!k || !v) {
            return nullptr;
        }
    
        pair<K, V>* pairs = new pair<K, V>[length];
        for (unsigned int i = 0; i < length; ++i) {
            pairs[i].first = *(k + i);
            pairs[i].second = *(v + i);
        }
        return pairs;
    }
    

    See demo

    If you dont want the copy. Maybe you should change the definition of pair, like

    template <typename K, typename V, K EmptyKey = K(-1)> struct pair {
        const K* first = nullptr;
        const V* second = nullptr;
        static constexpr auto empty_key = EmptyKey;
        bool empty() { return !first || *first == empty_key; }
    };
    

    The KVToPairs function is almost the same other than the pairs assignment part.

    See demo