【问题标题】:c++11 使用 lambda 排序列表
【发布时间】:2014-04-12 11:33:34
【问题描述】:

在练习使用 lambda 时,我编写了这个程序,它应该按 pairs 的第二个元素(int)对 list 进行排序。

#include 
#include 
#include 

使用命名空间标准;
主函数()
{
    list> s = {{"two", 2}, {"one", 1}, {"three", 3}};

    sort(s.begin(), s.end(), [](pair a, pair b) -> bool {
        返回 (a.second) > (b.second);
    });

    for_each(s.begin(), s.end(), [](pair a) {
        cout 

但我得到了这些错误:

c:\qt\qt5.2.0\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_algo.h:5513: error: no match for 'operator-' (operand types are 'std::_List_iterator<std::pair<std::basic_string<char>, int> >' and 'std::_List_iterator<std::pair<std::basic_string<char>, int> >')
     std::__lg(__last - __first) * 2, __comp);
                  ^

c:\qt\qt5.2.0\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_algo.h:2245: ошибка: 'void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<std::pair<std::basic_string<char>, int> >; _Compare = main()::__lambda0]', declared using local type 'main()::__lambda0', is used but never defined [-fpermissive]
     __final_insertion_sort(_RandomAccessIterator __first,
     ^

我的代码有什么问题?

【问题讨论】:

    标签: c++ list sorting c++11 lambda


    【解决方案1】:

    您不能将std::sortstd::liststd::forward_list 等顺序容器一起使用,因为它们没有标准算法std::sort 所需的随机访问迭代器。因此,这两个容器都有自己的成员函数 sort。

    在您的情况下,代码将如下所示:

    #include <iostream>
    #include <list>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        list<pair <string, int>> s = {{"two", 2}, {"one", 1}, {"three", 3}};
        s.sort( []( const pair<string,int> &a, const pair<string,int> &b ) { return a.second > b.second; } );
    
        for ( const auto &p : s )
        {
            cout << p.first << " " << p.second << endl;
        }
    }
    

    考虑到您需要包含标头&lt;string&gt;,否则您的程序将无法使用其他编译器进行编译。

    【讨论】:

      【解决方案2】:

      std::sort 需要随机访问迭代器,std::list 没有。但你可以改用std::list::sort

      s.sort([](const pair<string,int>& a, const pair<string,int>& b)
             {
               return (a.second) > (b.second);
             });
      

      我在其中创建了谓词 const 引用的参数,因为不需要复制它们,这样做可能会产生一些不必要的开销。

      【讨论】:

        猜你喜欢
        • 2012-08-21
        • 2015-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多