从功能中删除Vector中的元素

Ben*_*Ben 1 c++

在C++中,除了我的问题从Vector中删除元素之外,我如何将从向量中删除元素的方法概括为一个带有以下参数的函数:向量和要从此向量中删除的元素?

bool removeElementFromVector(vector * collection, void * element) {
    for(int i=0; i<collection->size(); i++){
        if (collection[i]==element){
            swap(collection[i], collection.back());
            collection.pop_back();
            return true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题在于我不知道参数列表是如何看起来的,以便能够与任何 vector<whatever*>和任何对象一起使用whatever!

编辑:解决方案:

myfunctions.h

template <typename T>
bool removeElementFromVector(vector<T> & collection, T const & element) { 
    // for... 
}
Run Code Online (Sandbox Code Playgroud)

myclass.h

#include "myfunctions.h"
public:
vector<Item*> items;                        
void removeItem(Item * item);          
Run Code Online (Sandbox Code Playgroud)

myclass.cpp

#include "myclass.h"
void myclass::removeItem(Item * item) {
    removeElementFromVector(this->items, item);
}
Run Code Online (Sandbox Code Playgroud)

ava*_*kar 5

您应该将该函数变为模板:

template <typename T>
bool removeElementFromVector(vector<T> & collection, T const & element);
Run Code Online (Sandbox Code Playgroud)

另外,不要使用指针.


Dav*_*eas 5

在C++中,编写将在不同类型上工作的通用代码的类型安全方法不是传递void*,而是模板.在您的特定情况下:

template <typename T>
void removeElement( std::vector<T> & collection, T const & element ) {
   collection.erase( std::remove( collection.begin(), collection.end(), element ),
                     collection.end() );
}
Run Code Online (Sandbox Code Playgroud)

通过在包含的类型上使用模板T,可以使其成为通用模板.在内部,用于从向量中移除元素的习语是擦除 - 移除习语,其将移除匹配的元素,并且向前压缩其余元素以维持相对顺序.我已经改变了引用的指针.如果你的容器持有指向给定类型,并通过该元素是一个指针类型,编译器会推断出Ttype*你,但上面的代码也将工作对于不持有指针容器(更通用的一个位)

如果相对顺序不重要,您可以使用您在问题中使用的相同循环,这将更有效(更少的副本数).