Search code examples
c++vectordynamic-memory-allocation

Multidimensional Dynamic Memory Vector c++


I do this program in c++. I want to build a table with random rows and 3 columns. When I compile there is no mistake but I execute the program do nothing and write nothing. Can you help me to find my error?

Thanks

int main(){
srand(time(0));
int project = (rand() % 5) + 1 ;   
std::cout << "The Number is " << project << "." << std::endl;

vector<vector<int> > P(project, vector<int>(3));

for(int i = 0; i <= P.size(); ++i){
  for(int j = 0;j <= P[i].size();++j){
        P[i][j] = (rand() % 50)+10;
        P[i][j] = (rand() % 2)+1;
        P[i][j] = (rand() % 50)+1;
  }
 }

 for(int a = 0;a <= P.size();++a){           
  for(int j = 0;j <= P[a].size();++j){
      std::cout << "Project "<< a <<" :"<< P[a][j] ;
        std::cout << P[a][j] <<" , ";
        std::cout << P[a][j] <<" ."<< std::endl;  
 }
 }

I get another problem it writes the same value for all the columns. So I need to change something in my loop right?


Solution

  • There are a couple of issues, you should be using size_t for the loops instead of int and you were going over by one in the loops. For example it should be i < P.size() instead of i <= P.size():

    for(size_t i = 0; i < P.size(); ++i)
    {
      for(size_t j = 0;j < P[i].size();++j)
      {
        P[i][j] = (rand() % 50)+10;
        P[i][j] = (rand() % 2)+1;
        P[i][j] = (rand() % 50)+1;
      }
     }
    

    Also, did you mean to write to the same entry, three times, what was the purpose of that? Also, you output the same entry three times as well. I modified to only output once:

    for(size_t a = 0;a < P.size();++a)
    {           
     for(size_t j = 0;j < P[a].size();++j)
     {
       std::cout << "Project "<< a <<" :"<< P[a][j] << std::endl;  
     }
    }
    

    Also if you are have using namespace std in your code I would advise against it. Just use std::vector explicitly.