c++ - 在 std::map 中插入 typedef 时出现问题

标签 c++

我在简单的 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;

到目前为止没有错误发生。出this我有这样做的想法,以减少阅读代码时的困惑。现在,当我想在 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 是否有问题我只是没有意识到 the post

编辑#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 insert方法重载。

DEMO


除此之外,考虑将 typedefs 更改为 type aliases:

using Generation_data_block = std::vector<uint8_t>;
// ...

因为这是自 C++ 11 以来做事的首选方式。

关于c++ - 在 std::map 中插入 typedef 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47855001/

相关文章:

指向 QGraphicsItem 的指针的 c++ 列表

c++ - boost python optional 引发错误

c++ - 为什么 pmr::string 在这些基准测试中这么慢?

c++ - 构建python时b2和./bootstrap.sh有什么区别

c++ - POCO - PropertyFileConfiguration 保存方法始终使用 ":"作为分隔符写入

c++ - 线程安全和 AfxMessageBox

c++ - 在 C++ 中使用 openmp 对数组进行并行求和

c++ - 为什么当我访问一个由三个整数组成的对象时,它会从基指针而不是堆栈指针中减去?

c++ - 从 C++ 调用 Haskell

c++ - 我需要一个 strcat_s() 的例子