Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

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

I have a video and for each frame, I am dividing into equally sized squares. Each video will have fixed frame dimensions, so the number of squares per video will not change (but different videos with different frame size will change, so the code must be dynamic).

I am trying to loop through each frame, and then loop through each square, and insert the square index and the square matrix into a dictionary. After the first frame, I want to append the square matrix to the vector value at its corresponding key. My code so far:

// 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]);
    }

What I am confused about is this line:

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

This line initializes the proper number of keys, but how do I insert the Mat value into the vector<Mat> structure for the first time, so I can then push_back to it in subsequent iterations?

I want the result to be something like this:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to do anything, and you don't need the insert call at all. The following will do everything you need:

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

std::unordered_map::operator[] will default-construct a new value if none with that key exists, so the first time a new value of i is encountered it will default-construct a new std::vector<Mat>, which you can then append the first value to.


Side note, using std::unordered_map<int, SomeType> for a contiguous sequence of keys is a bit odd. You've essentially created a less efficient version of std::vector at that point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...