Ujjwal
Ujjwal

Reputation: 23

Polymorphism between std::unordered_set and std::vector?

I have a function in my code which takes in a C++ container object, and reads each element in it using a loop. The function looks a bit like this:

void function(std::unordered_set<unsigned int> container)
{
    for(auto it = container.begin(); it != container.end(); it++)
    {
       /* Do something */
    }
}

However, I would like this function to also accept containers of type std::vector. As you can see from the code, the body of the function need not be aware of the type of the container (it can just access each element using *it). How can I achieve this without having redundancy in my code?

Upvotes: 1

Views: 298

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129374

Something like:

template<typename ContainerType>
void function(ContainterType container)
{
  ... 
}

should do what you want.

You need a template, becuase there isn't a common base-class for STL containers, so they aren't passable as "this is the baseclass, take any derived type".

Assuming you don't want to modify the container, I'd go with:

template<typename ContainerType>
void function(const ContainterType& container)
{
   ...
}

to avoid having a copy made.

Upvotes: 3

Matteo Italia
Matteo Italia

Reputation: 126807

For performance reasons and for a more "generic programming" (as opposed to OOP) view of the world or whatever STL containers aren't designed with polymorphism in mind; instead, as STL algorithms do, you are expected to expose a generic iterator-based interface and work with whatever iterator type that is given to you.

Upvotes: 2

Related Questions