So lets say I have a deque<int>. I also have an int* that points to a specific element x in the deque, but I don't know the index of x. Is there a way I can remove x from my deque with just a pointer to x?
So lets say I have a deque<int>. I also have an int* that points to a specific element x in the deque, but I don't know the index of x. Is there a way I can remove x from my deque with just a pointer to x?
Is there a way I can remove 'x' from my deque with just a pointer to x?
Yes, there is a way. Use linear search to find the element of the deque whose address is the same as the pointer. This should produce an iterator to the element that you want to remove. Pass that to deque::erase. There is a standard algorithm for linear search: std::find_if.
Note however that this search has incurs some overhead. You could avoid the search if you stored the iterator in the first place rather than a pointer. That said, the erasure itself has linear complexity (unless the element is at one of the ends), so the search doesn't make complexity asymptotically worse.
Also note that erasing the element of a deque invalidates all references including pointers and iterators to the container unless you erase from one of the ends (in which case only the references to the erased element are invalidated).
I join the previous comments,
Solving this problem can sollicit iterators (Boosted Pointers), maybe linear algorithms can achieve what you're expecting.
#include <iostream>
#include <deque>
#include <algorithm>
#include <functional>
int main()
{
int *ptr(0);
ptr=new int;
std::deque<int> values={1,2,3,4,5};
ptr=&values[3]; /*Let's seach for the number 4*/
std::function<void(int&)> lambda = [&](int& it)mutable throw()->
void { (&it == ptr)? values.erase(values.begin()+(&it-
&values[0])):values.begin();};
std::for_each(values.begin(), values.end(), lambda);
for(int& it :values){
std::cout<<it<<std::endl;
}
delete ptr;
*ptr=0;
return 0;
}
Please, if there are any errors, tell me, hope i've answered your task correctly.