0

I know this post can be a duplicate but the answers I could find aren't clear.

std::vector<EWindow> windows;
void closeWindow(EWindow* window);

These are my functions, I would like to erase the pointer EWindow* from the vector windows.
C++ Remove object from vector explain how to remove object but not a pointer.

  • You `windows` is a vector of `EWindow`, not `EWindow*`. If you want to contain pointers, use `std::vector windows`. Also it's probably best to use smart pointers, either `std::unique_ptr` or `std::shared_ptr`, depending on your needs. – Marco Pantaleoni Apr 30 '18 at 14:28
  • You could search and erase the corresponding `EWindow`, but what about those after it? All of the pointers pointing to them will be messed up... – Quentin Apr 30 '18 at 14:29
  • In fact, EWindow is an object to create a window more easily (like Qt) should I use pointers, smarts pointers or not? –  Apr 30 '18 at 14:34

1 Answers1

0

But you need to use vector of pointers to remove pointer. std::vector<EWindow*> windows; Code to remove pointer is from vector:

Declare your vector as vector of pointers:

std::vector<EWindow*> windows;

//...

void closeWindow(EWindow* window)
{
    //...
    auto RemoveIt = std::find(windows.begin(),windows.end(), window);
    if ( RemoveIt != windows.end() )
    {
        windows.erase(RemoveIt);
    }
    //...
}

Find element in vector then erase it from vector if it is there

Alexey Usachov
  • 1,364
  • 2
  • 8
  • 15
  • @Quentin sorry, fixed)) checked it on my ide on simple chars – Alexey Usachov Apr 30 '18 at 14:33
  • Thx a lot but In fact, EWindow is an object to create a window more easily (like Qt) should I use pointers, smarts pointers or not? –  Apr 30 '18 at 14:34
  • If OP's vector is indeed a vector of instances and not pointers to instances, this will not compile. – Quentin Apr 30 '18 at 14:36
  • @iRandomXx Yes you can use smart pointers instead of simple pointers. std::unique_ptr can help if there should be one instance in program, std::shared_ptr can help when there would be many pointers on one instance. They work on RAII idiom. You don't need to take care of delete pointers. – Alexey Usachov Apr 30 '18 at 14:42