簡體   English   中英

給定任意數量的整數,如何創建唯一鍵? 並使用該鍵存儲和以后從地圖中查找

[英]How to create a unique key, given arbitrary number of integers ? And use that key to store and later lookup from the map

因此,我試圖從任意數量的整數生成唯一鍵,以便以后可以使用該唯一鍵從地圖中查找值。 生成唯一密鑰時數字的順序無關緊要

我研究了各種選項,包括使用int生成元組,哈希和串聯生成密鑰,但找不到最佳解決方案。

預期的函數或邏輯應采用一個int數組,作為回報,它應提供一個唯一鍵(int)。

例如

樣本輸入可以是[1,5,6],[134,1] [6,5,1] [1,5,6]鍵應與[6,5,1]相同

據我了解您的問題(主要是從注釋推斷),您想在映射中放置一些數據結構,並使用整數數組作為鍵,其中整數的不同階數實際上應視為同一鍵。

就本例而言,假設“某些數據結構”是std::string ,那么最簡單的方法是使用std::set作為鍵,因為無論使用什么順序構造set1 5 6 1 6 56 5 1 ,得到相同的set

#include <string>
#include <map>
#include <iostream>

int main() {
    std::map< std::set<int>, std::string> x;
    x[ { 1,5,6} ] = "Hallo";    
    std::cout << x[ { 6 , 5, 1} ] << "\n";    
}

現場例子

僅使用set對元素進行排序有點浪費,因此您可以使用排序的向量。 為了防止地圖用戶需要對向量進行排序,可以使用輔助類型,如下所示:

#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <initializer_list>

struct sorted_vector {
    std::vector<int> x;
    sorted_vector(std::initializer_list<int> l) : x(l) {
        std::sort(x.begin(),x.end());       
    }
    bool operator<(const sorted_vector& other) const {
        return x < other.x;
    }
};

int main() {
    std::map< sorted_vector, std::string> x;
    x[ { 1,5,6} ] = "Hallo";    
    std::cout << x[ { 6 , 5, 1} ] << "\n";   
}

現場例子

我確實知道您擔心效率,尤其是當向量包含很多元素時。 但是,除非您真正達到極限或分析您的代碼並意識到您需要改進某些東西,否則我不會費心去重新發明輪子。

暫無
暫無

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

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