我正在嘗試將一長串鍵和值對轉換為一個映射,這樣我就可以對其進行迭代,而不是逐行定義它們,但是我混合了值的資料型別(uint8_t, uint16_t, uint32_t, 和uint64_t)。
這是我試圖構建映射的資料示例:
static constexpr uint8_t data1{0x01};
static constexpr uint16_t data2{0x0002};
static constexpr uint32_t data3{0x00000003};
static constexpr uint64_t data4{0x0000000000000004};
我試著做一個聯合和一個結構:
union/struct dtypes {
uint8_t i;
uint16_t j;
uint32_t k;
uint64_t l;
};
然后這是我創建地圖的嘗試:
std::map<std::string, dtypes> mymap = {{"data1", 0x01},
{"data2", 0x0002},
{"data3", 0x00000003},
{"data4", 0x0000000000000004}};
然后我嘗試做一個 for 回圈來填充uint8_t's 的向量(呼叫它vec):
for (auto iter = mymap.begin(); iter != mymap.end(); iter) {
byte_pushback(vec, iter->second)
};
但我得到的錯誤資訊是:
error: could not convert "'{{"data1", 0}, {"data2", 2}, and so on..' from '<brace-enclosed initializer list>' to 'std::map<std::__cxx11::basis_string<char>, dtypes>'
{"data4", 0x0000000000000004}};
^
|
<brace-enclosed initializer list>
我怎么能正確地做到這一點?
這個byte_pushback()函式將, uint16_t,uint32_t分解uint64_t成一堆uint8_ts 并向后推,所以.data2{0x00, 0x02}
uj5u.com熱心網友回復:
您應該像這樣初始化地圖。
std::map<std::string, dtypes> mymap = {
{"data1", {.i = 0x01}},
{"data2", {.j = 0x0002}},
{"data3", {.k = 0x00000003}},
{"data4", {.l = 0x0000000000000004}},
};
使用具有正確命名成員的聯合或結構有助于簡化編碼和解碼欄位的實作,并且有利于可讀性。
uj5u.com熱心網友回復:
我會怎么做看起來像這樣:
struct MyUnion {
int type;
uint8_t m8;
uint16_t m16;
uint32_t m32;
uint64_t m64;
};
class MyMap {
public:
void push(std::string key, uint8_t m8);
void push(std::string key, uint16_t m16);
void push(std::string key, uint32_t m32);
void push(std::string key, uint64_t m64);
bool has_key(std::string key) const;
bool is_8(std::string key) const;
bool is_16(std::string key) const;
bool is_32(std::string key) const;
bool is_64(std::string key) const;
uint8_t get_8(std::string key) const;
uint16_t get_16(std::string key) const;
uint32_t get_32(std::string key) const;
uint64_t get_64(std::string key) const;
private:
mutable std::map<std::string, MyUnion> mapimpl;
};
實作將如下所示:
void MyMap::push(std::string key, uint8_t m8) {
MyUnion u; u.type=0; u.m8 = m8;
mapimpl[key]=u;
}
bool MyMap::is_8(std::string key) const
{
return mapimpl[key].type==0;
}
uint8_t MyMap::get_8(std::string key) const
{
return mapimpl[key].m8;
}
剩下的函式has_key():
bool MyMap::has_key(std::string key) const
{
return mapimpl.find(key)!=mapimpl.end();
}
然后填充地圖將如下所示:
MyMap m;
m.push("key1",(uint8_t)0xff);
m.push("key2",(uint16_t)0xffff);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516303.html
標籤:C 字典c 11
上一篇:在Windows桌面應用程式(VS2022/C 14)中使用FirebaseSDK(VS2019/C 11)構建錯誤
下一篇:為什么需要閉包型別的參考成員?
