【问题标题】:Cast two pointers to a pointer of std::pair like struct将两个指针转换为 std::pair 的指针,如 struct
【发布时间】:2022-01-25 10:57:16
【问题描述】:

我有以下类似于std::pair 的简单结构。我想将两个指针keysValues 转换为pair 的指针。我该怎么做?

谢谢!

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; }
  };

【问题讨论】:

  • 由于内存布局不同(两个数组与一个交错数组),您需要将键/值复制到一个新数组中。

标签: c++ pointers templates key-value reinterpret-cast


【解决方案1】:

您必须将keysvalues 复制到对中。

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;
}

demo

如果您不想要副本。也许你应该改变pair的定义,比如

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; }
};

KVToPairs 函数除了pairs 赋值部分外几乎相同。

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2020-05-19
    • 2012-10-24
    • 1970-01-01
    • 2017-02-12
    相关资源
    最近更新 更多