在C++中,除了我的问题Erasing element from 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;
}
}
}
我在这里的问题是我不知道的参数列表如何有看起来像为了能够为这个与任何工作vector<whatever*>
和任何对象whatever
!?
编辑:解决方案:
myfunctions.h
template <typename T>
bool removeElementFromVector(vector<T> & collection, T const & element) {
// for...
}
myclass.h
#include "myfunctions.h"
public:
vector<Item*> items;
void removeItem(Item * item);
myclass.cpp
#include "myclass.h"
void myclass::removeItem(Item * item) {
removeElementFromVector(this->items, item);
}
矢量类是什么样的? std :: vector肯定会采用vector-> erase(element);例如。 – Valmond
@Valmond,'vector :: erase'是'O(n)',OP的方法是'O(1)'(尽管它扰乱了元素的顺序)。 – avakar
OP不关心订单;) – Ben