将指针转换为迭代器

convert pointer to iterator

本文关键字:迭代器 转换 指针      更新时间:2023-10-16

我有 2 个结构,它们相互指向

struct Person{
  string name;
  string born;
  int age;
  Id* p_id;
};
struct Id{
  string id_number;
  Person* p_person;
};

这些结构存储在两个称为vec_id和vec_person的结构的庞特向量中。我需要在vec_person中找到 Person 的函数,然后在向量 vec_id 中删除匹配的 Id。我的问题是将p_id转换为指针。

我的代码示例:

std::vector<Person*> vec_person;
std::vector<Id*> vec_id;
vector <Person*>::iterator lowerb=std::lower_bound (vec_person.begin(), vec_person.end(), Peter, gt);
//gt is matching function which is defined elsewhere
//peter is existing instance of struct Person
// lowerb is iterator, that works fine.
vec_id.erase((*lowerb)->p_id);
//gives error: no matching function for call to ‘std::vector<Person*>::erase(Person*&)’|
//if i can convert pointer (*low)->pnumber to iterator, it would be solved(i guess). 

感谢帮助大家

要将迭代器it转换为指针,请使用表达式 &*it

要将指向整数的指针右值(例如,...)转换为vector<int>::iterator,请使用以下声明:

  vector<int>::iterator it(...);

您不能只是从值(在本例中为指针)"转换"到迭代器。您必须在向量中搜索值并将其删除。您可以使用 std::remove_if 算法从范围中删除某些值。如果每个人都链接到一个 id,或者可能使用不同的容器(例如地图),您也可以考虑不保留两个向量。

我刚刚找到了这个解决方案

auto iter = vec.begin() + (pointer - vec.data());
auto p = std::equal_range( vec_person.begin(), vec_person.end(), Peter, gt );
if ( p.first != p.second )
{
   vec_id.erase( std::remove( vec_id.begin(), vec_id.end(), *p.first ), 
                 vec_id.end() );
}