如何在 C++ 中创建设置大小的字典并附加到循环中的向量值

How to create dictionary of set size and append to vector value in loop in c++

我有一个视频,我将每一帧分成大小相等的方块。每个视频都会有固定的帧尺寸,所以每个视频的方块数不会改变(但不同帧尺寸的不同视频会发生变化,所以代码必须是动态的)。

我试图遍历每一帧,然后遍历每个正方形,并将正方形索引和正方形矩阵插入到字典中。在第一帧之后,我想将方阵附加到其对应键处的向量值。到目前为止我的代码:

// let's assume list_of_squares is a vector that holds the Mat values for each square per frame
// also assuming unordered_map<int, vector<Mat>> fixedSquaredict; is declared in a .hpp file and already exists

for (int i=0; i<list_of_squares.size(); i++) {
    if (i=0) {
        fixedSquaredict.insert({i, list_of_squares[i]});
    }
    else {
        fixedSquaredict[i].push_back(list_of_squares[i]);
    }

我困惑的是这一行:

        fixedSquaredict.insert({i, list_of_squares[i]});

这一行初始化了正确数量的键,但是我如何 insert 第一次将 Mat 值放入 vector<Mat> 结构中,这样我就可以 push_back 在随后的迭代中?

我希望结果是这样的:

// assuming list_of_squares.size() == 2 in this example and it loops through 2 frames

list_of_squares = ((0, [mat1, mat2]),
                   (1, [mat1, mat2]))

您不需要做任何事情,您根本不需要 insert 调用。以下将完成您需要的一切:

for (size_t i = 0; i < list_of_squares.size(); ++i) {
    fixedSquaredict[i].push_back(list_of_squares[i]);
}

std::unordered_map::operator[] 将默认构造一个新值,如果 none 具有该键存在,因此第一次遇到 i 的新值时,它将默认构造一个新值std::vector<Mat>,然后您可以将第一个值附加到它。


旁注,对连续的键序列使用 std::unordered_map<int, SomeType> 有点奇怪。那时你基本上创建了一个效率较低的 std::vector 版本。