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
The three types of containers found in the STL are sequential, associative and unordered.
1) std::vector is a sequence container that encapsulates dynamic size arrays.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With