Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert pointer to iterator

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

like image 569
user2109307 Avatar asked Aug 13 '26 21:08

user2109307


2 Answers

To convert an iterator it to a pointer, use the expression &*it.

To convert a pointer-to-int rvalue (e.g., ... ) to a vector<int>::iterator, use the declaration:

  vector<int>::iterator it(...);
like image 67
Tom Payne Avatar answered Aug 16 '26 13:08

Tom Payne


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.

like image 31
Marius Bancila Avatar answered Aug 16 '26 14:08

Marius Bancila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!