I have function in C++ that takes a vector and pushes some items onto it. For example:
void MyFunction(vector<int>* output);
I want to modify it to be able to now take a vector or a hash_set. In Java, this would be easy, simply change the function to take a Collection (the common interface). All MyFunction does is put elements into the container it is given, so it shouldn’t have to care whether that container is a vector or a hash_set, only that there is some notion of “inserting” an element.
Thanks for your help!
He’d have a small issue doing a straight-up template. Vector typically uses push_back while hash_set would use insert.
Use a template, but use the insert function and insert at the .end() element so that the vector maintains fast operations – its your best bet. You’ll still slow down your hash-set a little though if it takes the insertion position as a hint of location (it’ll work though).
Using insert(iter, val), the contianer is extended by inserting new elements before the element at the iterator position. This is true for sequence containers (vector) while associative containers (hash_set) will just use the position as a hint – but the insertion will still work fine. The function below could be used to insert value U into any container supporting insert (all STL ones do) assuming U is the same as or implicitly convertible to the vector element type.