1
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?

2
  • 1
    Why do you think you need pointers? Commented Oct 9, 2011 at 22:07
  • 1
    It should look absolutely the same. What exactly goes wrong for you? The only notice is that perhaps you need to free a pointer before/after removing it from the vector. Commented Oct 9, 2011 at 22:13

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@user986789: No worries. Feel free to hit that "accept" button if you find the answer useful :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.