我有一個類Parent
,它從文件加載配置數據並在std::map
中創建Child
對象。 Child
對象由配置文件中定義的const char*
進行映射。對於任何給定Parent
,所有孩子將共享相同的密鑰長度。因此,一個Parent
的映射Child
對象可能有8個字節的密鑰,另一個Parent
的孩子可能會使用4個字節的密鑰。與memcmp比較的STL映射。如何在運行時設置比較塊大小?
如何使用方法described here或使用其他方法創建新的std::map
成員對象,該對象的比較函數依賴於僅在運行時可用的數據?
具體來說,我試圖用memcmp(a, b, n);
像以前鏈接的問題表明,但我想n
是可變的,而不是固定在4
如果我沒有解釋不夠好,我嘗試要做的,我會嘗試把它放在代碼中。我怎樣寫的compareKey
,以便它使用childKeyLength
比較映射鍵:如果你的鑰匙其實只是任意的二進制數據,你的意見建議,那麼也許你真正想要的是
class Child;
class Parent {
private:
struct compareKey {
bool operator()(char * const a, char * const b) {
return memcmp(a, b, childKeyLength) < 0;
}
};
std::map<const char*, Child, compareKey> children;
size_t childKeyLength;
public:
Parent(size_t childKeyLength)
: childKeyLength(childKeyLength) {};
}
爲什麼不使用'strcmp'? –
處理不一定以null結尾的二進制數據。 –
爲什麼首先使用'char *'?爲什麼不'std :: string'或'std :: vector'? –