In C++, in addition to my question Erasing element from Vector, how can I generalise the method for deleting an element from a vector into a function that takes the following arguments: the vector, and the element to be deleted from this 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;
}
}
}
My problem here is that I don’t know how the parameter-list has to look like in order to be able for this to work with any vector<whatever*> and any object whatever!?
EDIT: Solution:
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);
}
In C++, the type safe way to write generic code that will work on different types is not passing
void*, but rather templates. In your particular case:By using a template on the contained type
T, you make it generic. Internally, the idiom for removing the elements from the vector is the erase-remove idiom, which will remove the elements that match, and compact the rest of the elements forward maintaining the relative order. I have changed the pointers for references. If your container holds pointers to a given type, and the element passed is a pointer to that type, the compiler will inferTto betype*for you, but the code above will also work for containers that do not hold pointers (a bit more generic)If the relative order is not important, you can use the same loop that you had in your question, which will be more efficient (smaller number of copies).