How can I push_back data in a 2d vector of type int

前端 未结 6 878
借酒劲吻你
借酒劲吻你 2021-02-02 03:03

I have a vector and want to store int data in to it at run time can I store the data in a 2D vector in this manner ?

std::vector> n         


        
6条回答
  •  无人共我
    2021-02-02 03:18

    You are manipulating a vector of vectors. As such, when declaring normal it is empty and does not contain any element.

    You can either :

    Resize the vector prior to inserting elements

    std::vector > normal;
    normal.resize(20);
    
    for (size_t i = 0; i < normal.size(); ++i)
    {
        for (size_t j = 0; j < 20; ++j)
            normal[i].push_back(j);
    }
    

    This may be slightly more efficient than pushing an empty vector at each step as proposed in other answers.

    Use a flat 2D array

    If you want to store a 2D array, this is not the optimal solution, because :

    1. Your array data is spread across N different dynamically allocated buffers (for N lines)
    2. Your array can have a different number of columns per line (because nothing enforces that normal[i].size() == normal[j].size()

    Instead, you can use a vector of size N * M (where N is the number of lines and M the number of columns), and access an element at line i and columns j using the index i + j * N :

    size_t N = 20;
    size_t M = 20;
    std::vector normal;
    normal.resize(N * M);
    
    for (size_t i = 0; i < N; ++i)
        for (size_t j = 0; j < M; ++j)
            normal[i + j * N] = j;
    

提交回复
热议问题