我的问题看起来像这样:

  • 首先,您必须插入一些数字。
  • 下一个程序计算您在第一步中插入的数字的位数之和。
  • 将所有乐谱插入到称为vec
  • 的 vector 中

    问题是这样的:在程序末尾,您在步骤1中插入的​​所有数字都必须根据它们的数字总和进行排序(升序排列)。

    请注意!例如,如果两个数字(例如123和12300)具有相同的数字总和,则您必须按字典顺序对其进行排序。

    我不想自己创建函数,但我想使用库中的“sort”函数,但是我对此有疑问。是否可以对字典顺序也使用sort函数进行排序?有人可以帮我吗?
    输入示例:
    6
    13
    36
    27
    12
    4
    123
    

    预期产量:
    12
    13
    4
    123
    27
    36
    

    我的代码:
    #include<iostream>
    #include<cmath>
    #include<string>
    #include<vector>
    #include<sstream>
    #include<algorithm>
    using namespace std;
    
    int main()
    {
        vector<vector<int> > vec;
        int num;
        int n;
        cin >> n;
    
        for (int i = 0; i < n; i++)
        {
            cin >> num;
            vector<int> row;
    
            row.push_back(num);
    
            //conversion int to string:
            ostringstream ss;
            ss << num;
            string str = ss.str();
    
            int sum = 0;
            for (int g = 0; g < str.length(); g++){
                int pom = str[g] - '0';
                sum += pom;
            }
    
            row.push_back(sum);
            vec.push_back(row);
            row.clear();
        }
    
        //sort(vec[0][0], vec[vec.size()][0]);
    
        for (int i = 0; i < vec.size(); i++){
            for (int j = 0; j < 2; j++){
                //cout << vec[i][j] << " ";
            }
            cout << vec[i][0] << endl;
        }
    
    
    
        system("pause");
        return 0;
    }
    

    最佳答案

    您可以将每个数字存储为字符串,还可以预先计算其数字和,并将两者都保存在pair<int,string>中,然后将它们放入vector<pair<int,string>中并对其进行sort不需要自定义比较器std::pair的自定义比较器完全可以满足您的需求。

    // note: std::pair<std::string,int> would not work
    typedef std::pair<int,std::string> number;
    std::vector<number> numbers;
    
    // fill numbers such that number::first holds the digit sum
    // and number::second the number as string.
    // this is similar to your code
    
    std::sort(numbers.begin(), numbers.end());
    
    // now numbers are ordered as you want them
    

    关于c++ - 是否可以使用std::sort按字典顺序排序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28254456/

    10-11 22:38
    查看更多