【问题标题】:C++: std::merge => using for sorted listsC++:std::merge => 用于排序列表
【发布时间】:2017-02-02 00:13:18
【问题描述】:

我有两个排序列表。在我定义的函数 (sort_func) 之后,它们是这样排序的:

std::sort(list1.begin(), list1.end(), sort_func());

现在我想合并这两个列表。这应该既简单又高效,因为它们都已经以相同的方式排序了。

如果我使用std::merge,它会利用已经排序的列表吗?还是我应该编写自己的合并函数来更快?

我现在这样做:

std::merge(list1.begin(), list1.end(), list2.begin(), list2.end(), std::back_inserter(list), sort_func());

感谢您的建议!

【问题讨论】:

    标签: c++ sorting merge


    【解决方案1】:

    使用std::merge 的前提条件是两个列表都已排序。所以是的,它利用了这一点。

    将两个排序范围 [first1, last1) 和 [first2, last2) 合并到一个从 d_first 开始的排序范围。

    【讨论】:

      【解决方案2】:

      std::merge 要求对两个输入列表进行排序,因此它确实利用了这一点。无需自己构建。

      来自标准(N3242 §25.4.4.2):

      要求:范围 [first1,last1) 和 [first2,last2) 应根据 operator

      【讨论】:

        【解决方案3】:

        对于初学者来说,标准容器std::list 具有接受比较函数对象的成员函数merge。他们是

        template <class Compare> 
        void merge(list& x, Compare comp); 
        template <class Compare> 
        void merge(list&& x, Compare comp);
        

        所以你可以使用它们。

        因此,您可以选择使用标准算法 std::merge 或使用 std::list 的这些成员函数。

        考虑到如果您希望结果列表也根据此函数排序,则应使用用于对列表进行排序的相同比较函数sort_func()

        这是一个演示程序,展示了如何仅使用类std::list 的本机方法来完成任务。而不是你的比较函数,而是在标题&lt;functional&gt;中声明的函数对象std::greater

        #include <iostream>
        #include <list>
        #include <functional>
        
        int main() 
        {
            std::list<int> list1 = { 3, 1, 5, 9, 7 };
            std::list<int> list2 = { 8, 0, 4, 6, 2 };
        
            list1.sort( std::greater<int>() );
            list2.sort( std::greater<int>() );
        
            std::list<int> list( list1 );
        
            list.merge( list2, std::greater<int>() );
        
            for ( int x : list ) std::cout << x << ' ';
            std::cout << std::endl;
        
            return 0;
        }
        

        程序输出是

        9 8 7 6 5 4 3 2 1 0 
        

        【讨论】:

          猜你喜欢
          • 2023-04-05
          • 1970-01-01
          • 2012-05-13
          • 1970-01-01
          • 2017-04-26
          • 2014-04-30
          • 1970-01-01
          • 2011-09-30
          相关资源
          最近更新 更多