首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ STL map 自訂比較函式實現鍵值自動排序

     編輯:關於C++

std::map 預設以 std::less<Key> 排序鍵值。若鍵為 const char*,預設比較的是指標位址而非字串內容。本文示範如何撰寫仿函式(Functor)ltstr,使 map<const char*, int, ltstr> 依字典序自動排序,並給出完整可編譯範例。

仿函式實作

struct ltstr {
    bool operator()(const char* s1, const char* s2) const {
        return strcmp(s1, s2) < 0; // 字典序比較
    }
};

完整程式碼

#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;

struct ltstr {
    bool operator()(const char* s1, const char* s2) const {
        return strcmp(s1, s2) < 0;
    }
};

typedef map<const char*, int, ltstr> MYDATAMAP;
typedef MYDATAMAP::iterator IterMyData;

int main() {
    MYDATAMAP data;
    data.insert(MYDATAMAP::value_type("3", 9));
    data.insert(MYDATAMAP::value_type("4", 9));
    data.insert(MYDATAMAP::value_type("1", 9));
    data.insert(MYDATAMAP::value_type("2", 9));

    for (IterMyData it = data.begin(); it != data.end(); ++it)
        cout << "Key: " << it->first << " Value: " << it->second << endl;

    data.clear();
    return 0;
}

執行結果

Key: 1 Value: 9
Key: 2 Value: 9
Key: 3 Value: 9
Key: 4 Value: 9

現代 C++ 改寫建議(C++11 起)

  • 鍵改用 std::string,直接用預設 less<> 即可,避免指標生命週期管理風險。
  • 若必須用 C 風格字串,建議改用 std::string_view (C++17) 做鍵,並提供自訂 less<> 特化。
  • Lambda 寫法:auto cmp = [](const char* a, const char* b){ return strcmp(a,b)<0; }; 搭配 std::map<const char*, int, decltype(cmp)> m(cmp);。
「map 的比較函式必須滿足嚴格弱序;對字串鍵,優先選 std::string 或 string_view,讓標準庫處理記憶體與比較邏輯。」
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved