pushing back data into 2d vector in c++

别等时光非礼了梦想. 提交于 2019-12-11 22:54:03

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/26613246/pushing-back-data-into-2d-vector-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!