最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

c++ std::sort使用自定義的比較函數(shù)排序方式

 更新時(shí)間:2025年02月06日 08:51:05   作者:wjjontheway  
文章介紹了使用std::sort對(duì)容器內(nèi)元素進(jìn)行排序的基本方法,包括自定義排序函數(shù)和在類中調(diào)用自定義成員函數(shù)進(jìn)行排序的方法,文章還指出了在傳遞成員函數(shù)指針時(shí)可能會(huì)遇到的錯(cuò)誤,并提供了使用Lambda表達(dá)式的解決辦法

使用sort對(duì)容器內(nèi)元素進(jìn)行排序

  • std::sort()函數(shù)專門用來(lái)對(duì)容器或普通數(shù)組中指定范圍內(nèi)的元素進(jìn)行排序,排序規(guī)則默認(rèn)以元素值的大小做升序排序。
  • sort() 只對(duì) array、vector、deque 這 3 個(gè)容器提供支持
  • 可以自定義排序函數(shù)
#include <iostream>
#include <vector>
#include <algorithm>

// Define the pair type
typedef std::pair<uint32_t, uint64_t> PairType;

// Comparator function to compare pairs based on the second element (value)
bool comparePairs(const PairType& p1, const PairType& p2) {
    return p1.second > p2.second;
}

int main() {
    // Create the vector of pairs
    std::vector<PairType> vec = {
        {1, 100},   // idx=1, value=100
        {2, 50},    // idx=2, value=50
        {3, 200},   // idx=3, value=200
        // Add more pairs here if needed
    };

    // Sort the vector using the comparator function
    std::sort(vec.begin(), vec.end(), comparePairs);

    // Output the sorted vector
    for (const auto& pair : vec) {
        std::cout << "idx: " << pair.first << ", value: " << pair.second << std::endl;
    }

    return 0;
}

comparePairs是我們自定義的函數(shù),sort 第三個(gè)三處

 std::sort(vec.begin(), vec.end(), comparePairs);

在類中如何調(diào)用自定義的成員函數(shù)進(jìn)行排序

typedef std::pair<uint32_t, uint64_t> PairType;

bool MySort::comparePairs(const PairType& p1, const PairType& p2) {
    return p1.second > p2.second;
}

bool MySort::sort_fun(vector<PairType> vec)
{
    std::sort(vec.begin(), vec.end(), comparePairs); //報(bào)錯(cuò)
}

Visual Studio 報(bào)錯(cuò):

C3867    “MySort::compareParis”: 非標(biāo)準(zhǔn)語(yǔ)法;請(qǐng)使用 "&" 來(lái)創(chuàng)建指向成員的指針
C2672    “std::sort”: 未找到匹配的重載函數(shù)
C2780    “void std::sort(const _RanIt,const _RanIt)”: 應(yīng)輸入 2 個(gè)參數(shù),卻提供了 3 個(gè)

錯(cuò)誤原因

這個(gè)錯(cuò)誤是因?yàn)樵谑褂胹td::sort()時(shí),傳遞了一個(gè)成員函數(shù)指針,而非普通函數(shù)指針

解決辦法

使用Lambda表達(dá)式:

修改后的代碼:

typedef std::pair<uint32_t, uint64_t> PairType;

bool MySort::comparePairs(const PairType& p1, const PairType& p2) {
    return p1.second > p2.second;
}

bool MySort::sort_fun(vector<PairType> vec)
{
	// 定義Lambda表達(dá)式
	auto sortLambda = [this](const PairType& p1, const PairType& p2) {
        return this->comparePairs(a, b);
    };
    
	std::sort(vec.begin(), vec.end(), sortLambda); 
}

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

崇州市| 丹巴县| 锡林浩特市| 绥棱县| 韶关市| 香港| 麻阳| 永安市| 桐乡市| 札达县| 华阴市| 锦州市| 南宁市| 乃东县| 昭苏县| 五常市| 南郑县| 武山县| 镇赉县| 黄浦区| 常州市| 星子县| 定南县| 高雄市| 山阴县| 肃北| 垣曲县| 泽州县| 凤山县| 双柏县| 宁强县| 龙口市| 临江市| 邯郸县| 盈江县| 扎鲁特旗| 融水| 九江市| 庆阳市| 临澧县| 肇州县|