Search code examples
c++vector2dpush-back

Push back data into a 2D vector


I am trying to create a 2d vector of set size and then insert data into it. The issue I am having is being able to insert the data filling up each column and row in the 2d vector.

I have read through various other threads, but cannot find an implementation that works for me.

Here is some sample code for my issue:

int main()
{
    vector<string> strVec = { "a","b","c","d" }; 
    // letters to insert into vector                                        
    // this is just a sample case

    vector< vector<string>> vec;        // 2d vector
    int cols = 2;                       // number of columns 
    int rows = 2;                       // number of rows


    for (int j = 0; j < cols; j++)      // inner vec
    {
        vector<string>temp;             // create a temporary vec
        for (int o = 0; o < rows; o++)  // outer vec
        {
            temp.push_back("x");        // insert temporary value
        }
        vec.push_back(temp);            // push back temp vec into 2d vec
    }

    // change each value in the 2d vector to one
    // in the vector of strings
    // (this doesn't work) 
    // it only changes the values to the last value of the 
    // vector of strings
    for (auto &v : strVec)  
    {
        for (int i = 0; i < vec.size(); i++)
        {
            for (int j = 0; j < vec[i].size(); j++)
            {
                vec[i][j] = v;
            }
        }
    }

    // print 2d vec
    for (int i = 0; i < vec.size(); i++)
    {
        for (int j = 0; j < vec[i].size(); j++)
        {
            cout << vec[i][j];
        }
        cout << endl;
    }
}

Solution

  • You are assigning same string to all elements of vec again and again in the loop for (auto &v : strVec). That is, vec[0][0]=vec[0][1]=vec[1][0]=vec[1][1]=a, vec[0][0]=vec[0][1]=vec[1][0]=vec[1][1]=b, and so on.

    Removing this outer loop and assigning strVec[i*cols+j] to vec[i][j], we can get desired output.

    DEMO is here.

    for (int i = 0; i < vec.size(); i++)
    {
        for (int j = 0; j < vec[i].size(); j++)
        {
            vec[i][j] = strVec[i*cols+j];
        }
    }