簡體   English   中英

使用涉及地圖的比較器對項目向量進行排序

[英]Sort a vector of items with a comparator involving a map

我有一個用例,其中我將向量中的所有元素都映射到映射(哈希表)中的值。 我現在想使用存儲在地圖中的這些值對向量進行排序。

static map<string, string> canonForm;
static bool myfunction(string a, string b){
    return (canonForm[a] < canonForm[b]);
}

編輯:例如,在這里,canonForm將為我的向量中的每個字符串(鍵)保存字符串(值)。 上面的代碼段包含一個函數,我想將其用作比較器以對字符串向量進行排序。 我將如何實施呢? 上面的代碼片段在編譯過程中彈出錯誤。

請讓我知道是否可以進一步改善問題

這是如何執行此操作的示例。 參見內聯注釋:

#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>

// Note #1 - consider using an unordered_map here for better performance
static std::unordered_map<std::string, std::string> canonForm;

static bool myfunction(std::string const& a, std::string const& b)
{
    // Note #2 - use the `at` member-function - it works on const maps and does not create a new entry if the key is not found
    return canonForm.at(a) < canonForm.at(b);
}


void sort_by_canonform(std::vector<std::string>& keys)
{
    // Note #3 - simply supply myfunction as the comparison function
    std::sort(std::begin(keys), std::end(keys), myfunction);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM