pushing back data into 2d vector in c++

asker picture asker · Oct 28, 2014 · Viewed 7.9k times · Source
vector <int> col(0);
vector<vector<int> > row(0);

for(i=0;i<10;i++)
col.push_back(some integer);

row.push_back(col);
col.clear();

Can someone tell me what is wrong here? In the col[] vector, there is no error, but when I go to the next instruction by debug on line the before last line, just size of row[] changes to 1 from 0, but I can't see the values that it should take from the col[] vector?

Edit: I tried to put debug screen's screen-shot but reputation thing happened.

Answer

jpo38 picture jpo38 · Oct 28, 2014

There is definitely no problem with your code:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector< int > col(0);
    vector< vector<int> > row(0);

    for(int i=0;i<10;i++)
        col.push_back(i);

    row.push_back(col);
    col.clear();

    std::cout << "row size is: " << row.size() << std::endl;
    std::cout << "row 1st elem size is: " << row[0].size() << std::endl;
    std::cout << "col size is: " << col.size() << std::endl;

    return 0;
}

This outputs:

row size is: 1
row 1st elem size is: 10
col size is: 0

Which is perfectly expected. Could be a bug in your debugger (it may not show you the actual vector sizes).