将指针转换为迭代器

时间:2014-04-05 10:11:08

标签: c++ pointers iterator

我有2个结构,指向彼此

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

struct Id{
  string id_number;
  Person* p_person;
};

这些结构存储在两个ponters向量中,这些向量称为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). 

帮助帮助的人

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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

要将指针转换为rvalue(例如,...)转换为vector :: iterator,请使用声明:

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

develop
相关问题