Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                                                                                            
                
        
我目前正在尝试为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提供的容器或通用的std::sort

关于c++ - 如何为列表编写排序功能? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21330768/

10-11 22:39