Best way to remove std :: unique_ptr from a raw pointer vector?

So, I have a vector like this:

std::vector<std::unique_ptr<SomeClass>> myVector;

Then I have another vector containing the source pointers SomeClass:

std::vector<SomeClass*> myOtherVector;

If inside myOtherVectorthere is an element inside, it will also be inside myVector, so I want to go through each element in myOtherVectorand remove the same element from myVector. Then clean the vector. Here is what I came up with:

for(size_t i = 0; i < myOtherVector.size(); i++)
{
    myVector.erase(std::remove(myVector.begin(), myVector.end(), myOtherVector[i]), myVector.end());
}
myOtherVector.clear();

This leads to a compile-time error because it myVectorcontains unique pointers, but I provide remove()a raw pointer function. I need help here because I don’t know what the correct way to solve this problem would be. I changed the line to:

myVector.erase(std::remove(myVector.begin(), myVector.end(), std::unique_ptr<SomeClass>(myOtherVector[i])), myVector.end());

, std::unique_ptr, . myVector , - . , . , :

std::vector<std::shared_ptr<SomeClass>> myVector;
std::vector<SomeClass*> myOtherVector;

for(size_t i = 0; i < myOtherVector.size(); i++)
{
    myVector.erase(std::remove(myVector.begin(), myVector.end(), std::shared_ptr<SomeClass>(myOtherVector[i])), myVector.end());
}
myOtherVector.clear();

myVector.erase() , : "ApplicationName.exe ". "" .

, , - , , . ?

+5
3

. , , . .

remove_if (myVector) , , (myOtherVector); . -:

#include <vector>
#include <memory>
#include <algorithm>

struct SomeClass { /* ... */ };

int main()
{
    std::vector<std::unique_ptr<SomeClass>> myVector;
    std::vector<SomeClass*> myOtherVector;

    myVector.erase(
        std::remove_if( // Selectively remove elements in the second vector...
            myVector.begin(),
            myVector.end(),
            [&] (std::unique_ptr<SomeClass> const& p)
            {   // This predicate checks whether the element is contained
                // in the second vector of pointers to be removed...
                return std::find(
                    myOtherVector.cbegin(), 
                    myOtherVector.cend(), 
                    p.get()
                    ) != myOtherVector.end();
            }),
        myVector.end()
        );

    myOtherVector.clear();
}
+1

std::unique_ptr -, get, .

:

std::sort(myOtherVector.begin(), myOtherVector.end());

myVector.erase(std::remove_if(myVector.begin(), myVector.end(),
[&](std::unique_ptr<SomeClass> const& p) -> bool
{
    return std::binary_search(myOtherVector.begin(), myOtherVector.end(),
                              p.get());
}));

myOtherVector.clear();    
+3

, std:: set_difference kin (http://www.cplusplus.com/reference/algorithm/set_difference/)?

You will need to specify a comparison function to get () the raw pointer from unique_ptr

0
source

All Articles