c++ - Displaying vectors on Screen -
i have been doing reading how create set number of arrays , populate arrays using loops in c++. everywhere says need use vectors. have created arrays , populated them using vectors (i think). when compile , run displaying arrays, ok. when try display contents of arrays, program compiles ok crashes when run it.
i trying create 100 arrays size increasing 500 elements each time. (this assignment need test efficacy of algorithm.)
unsigned int numarrays = 100; unsigned int arraysize = 0; //create holder variable: unsigned int randomint = 0; //create arrays: std:vector<std::vector<int> > arrays(numarrays); for(std::size_t i=0; i< numarrays; i++){ arraysize = * 500; vector<int> temp; temp.reserve(arraysize); for(int j=0; j< arraysize; j++){ //generate random number: randomint = rand(); //add number array: temp.push_back(randomint); } arrays.push_back(temp); } for(int i=0; i<arrays.size(); i++){ cout << "{"; for(int j=0; j<arrays.at(i).size() - 1; j++){ cout << arrays.at(i).at(j) << ","; } cout << arrays.at(i).back() << "}" << endl; } i assume error somewhere in final nested loops not sure. in advance.
std:vector<std::vector<int> > arrays(numarrays); here initialize vector numarrays empty vector<int>s.
append new vectors. meaning have @ end 2*numarrays vectors.
the crash comes first half of vectors:
- the minus 1 in
j<arrays.at(i).size() - 1:size()returns unsigned 0, minus 1 maximum value. arrays.at(i).back()trying non existing last element.
to fix problem, replace line
std::vector<std::vector<int> > arrays(numarrays); by
std::vector<std::vector<int> > arrays; arrays.reserve(numarrays); and add test non-empty()ness before computing size() - 1.
Comments
Post a Comment