简体   繁体   中英

c++ dynamecly fill 2d vector when there is unknown rows or columns

i try to understand how can i hold dynamically 2d vector array ( or it can be other container in c++ ) that i can fill dynameclly when i dont know the row nuber and the column number in each raw what i have now is something like this but as you can see i have to define ahead the number of raws and columns

 std::vector<std::vector<BaseColumn*>> csv(1, std::vector<BaseColumn*> (1));
    std::string test = "d";
    Column<std::string>* tmpString = new Column<std::string>(Types::string,test);
    csv[0].push_back(tmpString);   
    csv[0].push_back(tmpString);
    csv[0].push_back(tmpString);
    csv[1].push_back(tmpString); //<--- Here im getting Segmentation fault
    csv[1].push_back(tmpString); 
    csv[1].push_back(tmpString); 
    csv[1].push_back(tmpString); 


Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007ff655703f1a in std::__new_allocator<BaseColumn*>::construct<BaseColumn*, BaseColumn*> (this=0x1af24052af8, __p=0xabababababababab) at C:/msys64/mingw64/include/c++/12.1.0/bits/new_allocator.h:175
175     { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

My question is simple how to construct 2d dynaic container...

std::vector<...> csv(1, ...);

Here you say that the vector have only one element. That means any index that is not equal to 0 will be out of bounds.

You probably want

std::vector<...> csv(2);  // Let the nested vectors be default-initialized and *empty*

If you don't know the size of the vector, at compile-time or at run-time (for example you read rows from a file of an unknown size) then just push back the inner vectors as you read the rows from the file:

std::vector<std::vector<BaseColumn*>> csv;  // Create an empty vector

std::string input_line;
while (std::getline(input_file_stream, input_line))
{
    std::vector<BaseColumn*> one_row = parse_line_into_columns(input_line);
    csv.push_back(one_row);  // Add the row
}

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