简体   繁体   中英

c++11 for each on 2D std::vector C not working?

Initialize a 2D vector called matrix.

std::vector<std::vector<int>> matrix(512,std::vector<int>(512));

Now I want to resize it:

This works:

    matrix.resize(50);
    for(int i = 0; i<matrix.size() ; i++)
        matrix[i].resize(50);

And this does not work:

    matrix.resize(50);
    for(auto ele : matrix)
        ele.resize(50);

I am using for(auto ele : container) in other places, I should have support for C++11, using Microsoft Visual C++ Compiler 12.0.

You are making copies of the inner vectors in each loop iteration. You need to use a reference:

for(auto& ele : matrix)
        ele.resize(50);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM