【发布时间】:2011-11-03 08:22:43
【问题描述】:
在 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;
}
}
}
我的问题是我不知道参数列表必须是什么样子才能使其能够与 any 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,
vector::erase是O(n),OP 的方法是O(1)(虽然它弄乱了元素的顺序)。 -
OP 不关心顺序 ;)
标签: c++