• C++set自定义string的比较函数


    C++set自定义string的比较函数

    目的:实现字符串的基于数字的排序。

    string a = "aaa1";
    string b = "aaa2";
    string c = "aaa10";
    

    比如这样,普通set 就会变成 a c b的顺序。现在需要的是 a b c的顺序。

    找了半天,也没找到我想要的,一搜索,全是什么自己包装一下string类型,然后重载自己写的类的比较。也是太久用模板,基础都忘了。

    代码:

    #include<iostream>
    #include<set>
    using namespace std;
    
    //随便自定义一个结构体,建立个set,一编译就会报错,弹出那个头文件才偶然发现。
    //所以有时间多看下这些源码也能收获满满。
    //来源于stl_function.h
    /*
    template<typename _Tp>
    struct less : public binary_function<_Tp, _Tp, bool>
    {
      bool
      operator()(const _Tp& __x, const _Tp& __y) const
      { return __x < __y; }
    };
    */
    //抱着试一试的态度,改一改,没想到正好能用
    template<typename _Tp>
    struct lessb //: public binary_function<string, string, bool>
    {
      bool
      operator()(const string& x, const string& y) const
      { 
      	int a = atoi(x.c_str()+3);
      	int b = atoi(y.c_str()+3);
      	return a<b;
      }
    };
    int main()
    {
    	string a = "aaa1";
    	string b = "aaa2";
    	string c = "aaa10";
    	string d = "aaa3";
    	set<string,lessb<string>> s;
    	s.insert(a);
    	s.insert(b);
    	s.insert(d);
    	s.insert(c);
    	for(auto i:s)
    	{
    		cout<<i<<endl;
    	}
    }
    

    运行结果:

    image

    后来发现,

    lessb前面加不加这个模板声明都不影响。当然了,set能用,其他的map啥的也是可以的。

    可用的代码:

    #include<iostream>
    #include<set>
    using namespace std;
    string prefix;//自己设定前缀 
    int len;//跳过前缀取整数 
    
    struct cmp{
    	bool operator()(const string& str1,const string& str2)
    	{
    		int num1 = atoi(str1.c_str()+len);
    		int num2 = atoi(str2.c_str()+len);
    		return num1<num2;
    	}
    };
    int main()
    {
    	set<string,cmp> s;
    	string str1 = "aaa1234";
    	string str2 = "aaa12";
    	string str3 = "aaa1";
    	string str4 = "aaa4";
    	cout<<"请输入前缀prefix:\n";
    	cin>>prefix;
    	len = prefix.length();
    	s.insert(str1);
    	s.insert(str2);
    	s.insert(str3);
    	s.insert(str4);
    	for(auto i:s)
    	{
    		cout<<i<<endl;
    	}
    }
    

    image

  • 相关阅读:
    Algorithm Gossip (37) 快速排序法 ( 一 )
    Algorithm Gossip (36) Heap排序法( 堆排序 )
    Algorithm Gossip (35) Shaker法
    Algorithm Gossip (34) 希尔排序
    AlgorithmGossip (33) 选择、插入、气泡排序
    Algorithm Gossip (32) 得分排行
    Algorithm Gossip (31) 数字拆解(dp问题)
    Algorithm Gossip (30) m元素集合的 n 个元素子集
    Algorithm Gossip (29) 产生可能的集合
    Algorithm Gossip (27) 排列组合
  • 原文地址:https://www.cnblogs.com/dayq/p/16114021.html
Copyright © 2020-2023  润新知