• c++ list sort


    // list::sort
    #include <iostream>
    #include <list>
    #include <string>
    #include <cctype>
    
    // comparison, not case sensitive.
    bool compare_nocase (const std::string& first, const std::string& second)
    {
      unsigned int i=0;
      while ( (i<first.length()) && (i<second.length()) )
      {
        if (tolower(first[i])<tolower(second[i])) return true;
        else if (tolower(first[i])>tolower(second[i])) return false;
        ++i;
      }
      return ( first.length() < second.length() );
    }
    
    int main ()
    {
      std::list<std::string> mylist;
      std::list<std::string>::iterator it;
      mylist.push_back ("one");
      mylist.push_back ("two");
      mylist.push_back ("Three");
    
      mylist.sort();
    
      std::cout << "mylist contains:";
      for (it=mylist.begin(); it!=mylist.end(); ++it)
        std::cout << ' ' << *it;
      std::cout << '
    ';
    
      mylist.sort(compare_nocase);
    
      std::cout << "mylist contains:";
      for (it=mylist.begin(); it!=mylist.end(); ++it)
        std::cout << ' ' << *it;
      std::cout << '
    ';
    
      return 0;
    }

     以上是用string 模版写的可以自定义方法对list.sort();

    可参考http://www.cplusplus.com/reference/list/list/sort/

    2.list sort 模版如何使用

    void sort( ); 
    template<class Traits> 
       void sort(
          Traits _Comp
       );
    可参考http://technet.microsoft.com/zh-cn/library/kz841ss7(v=vs.90)

    3.如果一个list 放的student 包含name(string) age(int).
    如何用list.sort()方法分别排序?
    首先写个
    bool compare_nocase (const std::string& first, const std::string& second)
    {
      unsigned int i=0;
      while ( (i<first.length()) && (i<second.length()) )
      {
        if (tolower(first[i])<tolower(second[i])) return true;
        else if (tolower(first[i])>tolower(second[i])) return false;
        ++i;
      }
      return ( first.length() < second.length() );
    }方法
    然后
     mylist.sort(compare_nocase);就行了




  • 相关阅读:
    SQL Server 日期函数:某天是星期几?
    DZNEmptyDataSet,优秀的空白页或者出错页封装
    SVN文件排除
    Android开发艺术探索读书笔记——进程间通信
    HDU 2110 Crisis of HDU
    Android4.4之后休眠状态下Alarm不准时的问题
    Android App性能測试
    Java笔试面试题整理第一波
    美国大学计算机专业
    js 開始时间,当前时间,结束时间的比較
  • 原文地址:https://www.cnblogs.com/yelongsan/p/4091943.html
Copyright © 2020-2023  润新知