0

Taken from C++ Erase vector element by value rather than by position?

The answer states that if you have a vector of int's you can use the erase-remove idiom to remove an element by it's value like so:

vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

Where 8 is an element in the list.

My question is, using this same technique is it possible to remove a pointer element with a pointer as a value like so:

std::vector<T*> m_list;

T* value;
m_list.erase(std::remove(m_list.begin(), m_list.end(), value), m_list.end());

Given that "value" is an element in the list.

Community
  • 1
  • 1
Belfer4
  • 351
  • 3
  • 11
  • Yes, of course. It's not the `int`s that's important, it's that they're equality-comparable against the value you pass in. And even that's not important, since you could use `remove_if` instead. – Barry Aug 18 '15 at 16:35
  • This may cause a memory leak if the pointer were dynamiclly alocated. Look at using [smart pointers](https://en.wikipedia.org/wiki/Smart_pointer) instead of raw pointers – NathanOliver Aug 18 '15 at 16:36
  • If the vector owns allocated pointers, erase is a memory leak. –  Aug 18 '15 at 16:37
  • @NathanOliver In my case the use of smart pointers is not an option. Is there a way to remove it and make sure it doesn't leak? – Belfer4 Aug 18 '15 at 16:42
  • If by `remove it` you mean erase then AFAIK no. Why can't you use smart pointers? If you can't use C++11 boost has them. – NathanOliver Aug 18 '15 at 16:43
  • @Belfer4 The remove itself, does not produce a memory leak (if the vector owns allocated pointers) –  Aug 18 '15 at 16:43

0 Answers0