溫馨提示×

C++ cmp函數(shù)在不同數(shù)據(jù)結(jié)構(gòu)中的應(yīng)用

c++
小樊
83
2024-09-09 09:00:20
欄目: 編程語言

在 C++ 中,cmp 函數(shù)通常用作比較器,用于定義排序規(guī)則或自定義數(shù)據(jù)結(jié)構(gòu)的相等性判斷。它可以在多種數(shù)據(jù)結(jié)構(gòu)中使用,例如:

  1. 排序算法:在排序算法(如 std::sort)中,cmp 函數(shù)可以用來定義元素之間的排序規(guī)則。例如:
#include<algorithm>
#include<vector>
#include<iostream>

bool cmp(int a, int b) {
    return a > b; // 降序排列
}

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5, 9};
    std::sort(v.begin(), v.end(), cmp);

    for (int i : v) {
        std::cout << i << " ";
    }
    return 0;
}
  1. 優(yōu)先隊(duì)列(堆):在優(yōu)先隊(duì)列(如 std::priority_queue)中,cmp 函數(shù)可以用來定義元素的優(yōu)先級。例如:
#include<queue>
#include<iostream>

bool cmp(int a, int b) {
    return a > b; // 最小堆
}

int main() {
    std::priority_queue<int, std::vector<int>, decltype(&cmp)> pq(cmp);
    pq.push(3);
    pq.push(1);
    pq.push(4);

    while (!pq.empty()) {
        std::cout << pq.top() << " ";
        pq.pop();
    }
    return 0;
}
  1. 關(guān)聯(lián)容器:在關(guān)聯(lián)容器(如 std::map、std::set)中,cmp 函數(shù)可以用來定義元素的排序規(guī)則。例如:
#include <map>
#include<iostream>

bool cmp(const std::string &a, const std::string &b) {
    return a.size() < b.size(); // 按字符串長度排序
}

int main() {
    std::map<std::string, int, decltype(&cmp)> m(cmp);
    m["apple"] = 1;
    m["banana"] = 2;
    m["cherry"] = 3;

    for (const auto &p : m) {
        std::cout << p.first << ": " << p.second<< std::endl;
    }
    return 0;
}

請注意,在這些示例中,我們使用了 C++11 的 lambda 表達(dá)式來定義 cmp 函數(shù)。你也可以使用普通的函數(shù)指針或者自定義的比較類。

0