[英]Problems inserting typedef in std::map
我在簡單的std::map
插入一些typedef時遇到了一個奇怪的問題。 我定義了三種類型:
typedef std::vector<uint8_t> Generation_block;
typedef std::vector<Generation_block> Generation_blocks;
typedef std::map<uint32_t, Generation_blocks> Generations_map;
到目前為止,沒有錯誤發生。 出於這種考慮,我想到了這種方式來減少閱讀代碼時的混亂。 現在,當我想在地圖中插入一些值時,情況變得更糟:
Generation_block = gen_block; //gets filled with some uint8_t data
Generation_blocks = gen_blocks; //gets filled with some Generation_block
Generations_map gen_map;
uint32_t generation_id; //gets set to several values identifiying the packet generation (for rlnc network coding purposes)
gen_map.insert(generation_id, gen_blocks); //error occurs
最后一行產生錯誤:
error: no matching function for call to ‘std::map<unsigned int, std::vector<std::vector<unsigned char> > >::insert(uint32_t&, Generation_blocks&)’
gen_map.insert(gen_id, gen_blocks);
但是我真的不明白我在做什么錯。 有人有建議嗎? 是否有與自己的typedef我只是沒有意識到出了問題的帖子 ?
編輯#1:
因此,我建立了一個最小的示例:
#include<vector>
#include<cstdint>
#include<map>
#include<random>
typedef std::vector<uint8_t> Generation_data_block;
typedef std::vector<Generation_data_block> Generation_blocks;
typedef std::map<uint32_t, Generation_blocks> Generations_map;
int main(){
Generations_map gen_map;
for(int j=0; j < 10; j++){
Generation_blocks gen_blocks;
for(int i = 0; i < 10; i++){
Generation_block gen_block;
std::generate(gen_block.begin(), gen_block.end(), rand); //generating randm data
gen_blocks-push_back(gen_block);
}
uint32_t generation_id = j;
gen_map.insert(generation_id, gen_blocks);
}
}
gen_map.insert(generation_id, gen_blocks);
您不能以這種方式將元素插入到std::map
中。
您需要將代碼更改為:
gen_map.insert(std::make_pair(generation_id, gen_blocks));
或者,簡單地:
gen_map.insert({generation_id, gen_blocks});
與std::map
插入方法重載兼容。
除此之外,考慮將typedef更改為類型別名 :
using Generation_data_block = std::vector<uint8_t>;
// ...
自從C ++ 11以來,它是做事情的首選方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.