0

Does C++ have a common base class for sorted containers like std::set or std:map?

Background: I want to implement a generic function which deletes all elements in a container which are not found in another container. As a precondition I want to define that the passed containers must be sorted.

user1056903
  • 921
  • 9
  • 26
  • 7
    http://en.cppreference.com/w/cpp/algorithm/set_difference – LogicStuff Oct 11 '16 at 13:05
  • To answer your question: No, because the standard does not say so. If there are, it is an implementation detail and the inheritance is probably `private`. – LogicStuff Oct 11 '16 at 13:05
  • 1
    if you want to create generic code for the STL templates are most likely your way to go – Hayt Oct 11 '16 at 13:06

2 Answers2

2

Does C++ have a common base class for sorted containers like std::set or std:map?

No, these don't have a common base class.

You can use their specific iterator types to rely on commonalities in a templated implementation.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

Doesn't has a generic class.

But they have a similar mechanism: Iterators. Let me put a example:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <list>

using namespace std;

template<class InputIterator>
void printContainer(InputIterator begin_it,InputIterator end_it)
{
    while (begin_it != end_it)
    {
        cout << (*begin_it) << ' ';
        begin_it++;
    }

    cout << endl;
}

int main()
{
    vector<int> vector_data;
    list<int> list_data;

    srand(time(0));

    for (int i = 0;i < 5;i++)
    {
        int n = rand() % 10;
        vector_data.push_back(n);
        list_data.push_back(n);
    }

    printContainer(vector_data.begin(),vector_data.end());
    printContainer(list_data.begin(),list_data.end());
}

Check algorithm library, it has functions for generic containers: http://www.cplusplus.com/reference/algorithm/

amchacon
  • 1,891
  • 1
  • 18
  • 29