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.
精彩评论