【问题标题】:How can I write a sort function for list? [closed]如何为列表编写排序函数? [关闭]
【发布时间】:2014-02-15 08:02:05
【问题描述】:

我目前正在尝试为 list 编写排序函数。我的代码是:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <list>
#include <string>
using namespace std;

template<typename T>
void sort(T &mylist)
{ 
        typename std::list<T>::iterator it1;
        typename std::list<T>::iterator it2;
        for(it1=mylist.begin();it1!=mylist.end();it1++)
            for(it2=mylist.begin();it2!=mylist.end()-it1;it2++)
                if((*((it2)+1))<*it2)
                    swap((*((it2)+1)),*it2);
             cout << *it1 << ' ';
}    
int main()
{   
        list<int> List;
        List.push_back(1); 
        List.push_back(12); 
        sort(List);
        return 0;
}

编译失败:

  error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::_List_iterator<_Mylist>' (or there is no acceptable conversion)
  error C2784: ''unknown-type' std::operator -(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'std::_List_iterator<_Mylist>'
  error C2676: binary '-' : 'std::_List_iterator<_Mylist>' does not define this operator or a conversion to a type acceptable to the predefined operator
  error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::list<_Ty>' (or there is no acceptable conversion)

您能帮我找出问题所在吗?

【问题讨论】:

  • sort(List),而不是sort(&amp;List)。你混淆了指针和迭代器。

标签: c++ list function


【解决方案1】:

您的函数需要引用,请将其与sort(List); 一起使用。

注意:除非您将此作为练习,否则最好使用提供的容器sort 或通用的std::sort

【讨论】:

    【解决方案2】:

    sort(&amp;List) 更改为sort(List)

    【讨论】:

      【解决方案3】:
      1. 您的函数接受T&amp; 类型的参数,但随后将其视为std::list&lt;T&gt;。该函数应该采用std::list&lt;T&gt;&amp;,或者您应该将迭代器声明为T::iterator 类型。
      2. it2!=mylist.end()-it1 表达式对我来说没有意义。您真的是要从另一个迭代器中减去一个迭代器吗?我认为链表迭代器不支持这一点。结果肯定不会是另一个迭代器,所以你不能比较它。也许最后的-it1 不应该在那里?

      【讨论】:

        猜你喜欢
        • 2017-04-05
        • 2017-10-10
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 2014-05-10
        • 2013-12-15
        • 2019-10-17
        • 2011-01-11
        相关资源
        最近更新 更多