Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign values into a 2D vector like a 2D array

Is there anyway to do it? Currently I use like this:

for( i=0;i<PU_number;i++)
{
    for( j=0;j<=time_slots;j++)
        myMatrix.tempVec.push_back(0.0);
    myMatrix.value.push_back(myMatrix.tempVec);
    myMatrix.tempVec.clear();
}

However, it is not useful for me. Sometimes I need to change a particular adress in this vector. like myMatrix.tempVec[1][4]. When I do it like this:

myMatrix.value[i][j]=value;

it corrupts memory, I get SIGABRT, SIGSESV and lots of thing like them. Also valgrind gets crazy when I do that. But I need an appropriate way to do it.

EDIT: I did what you guys said:

myMatrix.value.resize(PU_number);
for( i=0;i<PU_number;i++)
    myMatrix.value[i].resize(time_slots);

and then:

for( i=0;i<PU_number;i++)
{
    for( j=0;j<time_slots;j++)
    {
        for( k=0;k<number_of_packets;k++)
        {
            double r=((double) rand() / (RAND_MAX));
                for( x=myMatrix.mat[i][k];x<=myMatrix.mat[i][k]+myMatrix.len[i][k];x++)
                myMatrix.value[i][x]=r;

        }
    }
}

And I got "Invalid write of size 8" again in valgrind.


2 Answers

There's the std::vector::resize() function, that can be used to set the dimensions of your matrix properly, before you access any values by indexing.

Here's a small sample

myMatrix.resize(PU_number);
for( i=0;i<PU_number;i++) {
    myMatrix[i].resize(time_slots);
    for( j=0;j<=time_slots;j++)
        myMatrix[i][j] = 0.0;
}
like image 60
πάντα ῥεῖ Avatar answered May 08 '26 17:05

πάντα ῥεῖ


You can use a std::vector > like here :

#include <vector>
#include <iostream>
int main()
{
  std::vector<std::vector<int> > vec;
  vec.resize(10);
  for (unsigned int i = 0 ; i < vec.size(); ++i)
    {
      vec[i].resize(10);
    }
  vec[1][4] = 3;
  vec[1].push_back(5)
  std::cout << "vec[1][4] = " << vec[1][4] << std::endl;
  std::cout << "vec[1][10] = " << vec[1][10] << std::endl;
  return (0);
}

I create a vector of size 10 which contain others vector of size 10; note that you have to use resize to get the size with a std::vector > but after if you want to add a size you can use vec[i].push_back(5);

like image 21
Gabriel de Grimouard Avatar answered May 08 '26 15:05

Gabriel de Grimouard