将指针转换为迭代器 [英] convert pointer to iterator

查看:835
本文介绍了将指针转换为迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个结构,指向对方

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

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

这些结构体存储在两个向量的ponters向量结构中,称为ve​​c_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是在其他地方定义的匹配函数
// peter是struct Person的现有实例
// lowerb是迭代器,工作正常。
vec_id.erase((* lowerb) - > p_id);
//给出错误:没有匹配的函数调用'std :: vector< Person *> :: erase(Person *&)'|
//如果我可以转换指针(*低) - > pnumber到迭代器,它会被解决(我猜)。

Thx帮助人

方案

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


I have 2 structs, that point to each other

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

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

those structs are stored in two vectors of ponters to those structures called vec_id and vec_person. I need function which finds Person in vec_person, and then deletes matching Id in vector vec_id. My problem is converting p_id to pointer.

example of my code :

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). 

Thx for help guys

解决方案

You can't just 'convert' from a value (pointer in this case) to an iterator. You'd have to search for the value inside the vector and remove it. You could use the std::remove_if algorithm to remove certain values from a range. You might also consider not keeping two vectors if each Person is linked to an id, or maybe using a different container, such as a map.

这篇关于将指针转换为迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆