DataMiner
DataMiner

Reputation: 325

Finding and deleting an element from a vector of pointers?

vector<unsigned int> x;
vector<unsigned int>::iterator itr;
unsigned int varF;
...
....

// find and delete an element from a vector.
itr = std::find(x.begin(), x.end(), varF);  // <algorithm>
if (itr != x.end()) 
x.erase(itr);
//or
x.erase(std::remove(x.begin(), x.end(), varF), x.end()); 

I want to convert this vector to a vector of pointers

vector<unsigned int*> x;

How I can convert the above functionality for a vector of pointers?

Upvotes: 1

Views: 2183

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477700

Use find_if instead of find, or remove_if instead of remove, to employ a custom predicate:

struct FindIntFromPointer
{
  FindIntFromPointer(int i) : n(i) { }
  bool operator()(int * p) const { return n == *p; }
private:
  int n;
};

std::find_if(x.begin(), x.end(), FindIntFromPointer(varF));
x.erase(std::remove_if(x.begin(), x.end(), FindIntFromPointer(varF)), x.end());

If you have C++11, you can use a lambda instead of the explicit predicate:

std::find_if(x.begin(), x.end(), [varF](int * p) -> bool { return varF == *p; });

The predicate could be turned into a template if you want to reuse it for other similar situations where you need to dereference-and-compare. If this is the case, a template is more elegant than typing out the lambdas each time.

Upvotes: 8

Related Questions