Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the base class for STL containers list, deque, vector etc.?

I want to write a function that can take either of STL generic list, deque or vector and search for a key in it. What would be method signature of this function and how can we implement it?

What I know is that if we are accepting any of the derived classes in function argument we can use base abstract class assuming all relevant derived ones have the functions you need for your question.

EDIT: We cannot pass container's iterators in the function argument. If we can that is easy. It has to be a container.

I was thinking: Assuming 'Container' is an abstract base class from STL containers (which its not, according to first answer below).

template bool Search(std::Container C, T& key);

Thanks

like image 795
shaffooo Avatar asked Feb 22 '16 20:02

shaffooo


People also ask

What are STL container classes?

The three types of containers found in the STL are sequential, associative and unordered.

What kind of container is the STL vector?

1) std::vector is a sequence container that encapsulates dynamic size arrays.

Is vector an STL container?

The STL vector Container. The vector class implements a dynamic array that provides fast insertion at the end, fast random access to its components, and automatically resizes itself when components are inserted or deleted.


1 Answers

As SergeyA mentioned in his answer, C++'s STL does not have polymorphic containers (opposing to Java or C# interfaces).

Regarding your requested function signature, look into STL <algorithm> header. There are lot of functions operating on some data, using two pointers (iterators) to the beginning and end of data block. For example,

template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );

searching for some value in [first, last).

If you really want to pass whole container to the function, you'll similarly write

template<class Container, class T>
bool Search(const Container& container, const T& value)
{
    for (auto iterator = container.begin(); iterator != container.end(); ++iterator)
    {
        if (*iterator == value)
            return true;
    }
    return false;
}
like image 155
Zereges Avatar answered Oct 09 '22 02:10

Zereges