【问题标题】:Base class of sorted containers in C++C++中排序容器的基类
【发布时间】:2016-10-11 13:03:00
【问题描述】:

C++ 是否有用于排序容器(如 std::set 或 std:map)的通用基类?

背景:我想实现一个通用函数,它删除一个容器中没有在另一个容器中找到的所有元素。作为先决条件,我想定义传递的容器必须进行排序。

【问题讨论】:

  • 回答你的问题:不,因为标准没有这样说。如果有,就是一个实现细节,继承大概是private
  • 如果您想为 STL 模板创建通用代码,那么您很可能会这样做

标签: c++ containers stdmap stdset


【解决方案1】:

C++ 是否有用于排序容器(如 std::set 或 std:map)的通用基类?

不,它们没有共同的基类。

您可以使用它们特定的iterator 类型来依赖模板化实现中的共性。

【讨论】:

    【解决方案2】:

    没有泛型类。

    但它们有一个相似的机制:迭代器。我举个例子:

    #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());
    }
    

    检查算法库,它具有通用容器的功能: http://www.cplusplus.com/reference/algorithm/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-22
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      相关资源
      最近更新 更多