如何查找指向数组中元素的指针的索引
How to find the index of a pointer that points to an element in an array?
所以我正在尝试编写一个将元素添加到我的数组的方法。我的 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
。
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int