vector排序/vector按照自定义规则排序(c++)

1. vector排序

#include
#include
#include //内含sort函数
using namespace std;

int main() {
    vector<string> vec = { "cab", "abc", "cba" };
    sort(vec.begin(), vec.end());
    for (auto s : vec) { cout << s << endl; } //显示排序后的vec
    return 0;
}

排序前:vec = { "cab", "abc", "cba" };
排序后:vec = { "abc", "cab", "cba" };

2. vector按照自定义规则排序

(剑指offer:把数组排列成最小的数)

class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        sort(numbers.begin(), numbers.end(), cmp);
        string ans = "";
        for (auto n : numbers) {
            ans += to_string(n);
        }

        return ans;
    };

    static bool cmp(int a, int b) { //定义比较规则时static很重要,否则可能报错
        string ab = to_string(a) + to_string(b);
        string ba = to_string(b) + to_string(a);
        return ab < ba;
    } 
};

你可能感兴趣的:(c++,数据结构与算法)