如何查找指向数组中元素的指针的索引

How to find the index of a pointer that points to an element in an array?

本文关键字:数组 元素 指针 索引 何查找 查找      更新时间:2023-10-16

所以我正在尝试编写一个将元素添加到我的数组的方法。我的 find_key(( 方法返回一个指针,该指针指向等于或大于现有数组中找到的元素的元素。有没有办法找到我的指针从 find_key(( 指向的元素的索引?

这是我到目前为止正在使用的内容

template<typename K, typename V>
bool MapSet<K,V>::add(Node<K,V> n)
{
  Node<K, V> *ptr = find_key(n.first);
  if (size() == capacity_)
  {
    capacity_ *= 2; // Double capacity
    auto *new_data = new [capacity_]; // New array with double capacity
    copy(ary_, ary_+last_, new_data); // Copy over
    swap(ary_, new_data); // Swap pointers
    delete [] new_data; // Delete old array pointer (old since swapped)
  }
  if (size() == 0)
  {
    ary_[0].first = n.first;
    ary_[0].second = n.second;
    return true;
  }
  else if (ptr == ary_+last_)
  {
    ary_[ptr].first = n.first;
    ary_[ptr].second = n.second;
    return true;
  }
  else if ((*ptr) == n.first)
  {
    return false;
  }
  else if ((*ptr) !== n.first)
  {
    ary_[ptr-1].first == n.first;
    ary_[ptr-1].second == n.second;
    return true;
  }
}

由于您使用的是指针,因此只需从找到的指针中减去指向数组中第一个元素的指针,即可将索引放入数组中。所以

Node<V, K>* ptr = ...
size_t index = static_cast<size_t>(ptr - ary_);

应该可以解决问题(如果数组来自类型 Node<V, K>[] (。如果您的类支持迭代器,您也可以改用std::distance