user2109307
user2109307

Reputation: 123

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

Upvotes: 2

Views: 14732

Answers (4)

Tom Payne
Tom Payne

Reputation: 79

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

Upvotes: 6

Vafa Sadri
Vafa Sadri

Reputation: 49

I just found this solution

auto iter = vec.begin() + (pointer - vec.data());

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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

Upvotes: 0

Marius Bancila
Marius Bancila

Reputation: 16328

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.

Upvotes: 3

Related Questions