简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM