Jump to content

STL vector to two-dimensional array

- - - - -

  • Please log in to reply
1 reply to this topic

#1
Apprentice123

Apprentice123

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 430 posts
How do I transform a vector in a two-dimensional array ?


I try:


vector<int> v;
v.push_back(0)
v.push_back(1)
v.push_back(2)
v.push_back(3)
v.push_back(4)
v.push_back(5)
v.push_back(6)
v.push_back(7)
v.push_back(8)


int m[3][3] = {(v[0], v[1], v[2]),
               (v[3], v[4], v[5]),
               (v[6], v[7], v[8])};


for(int i=0; i<3; i++){
            for(int j=0; j<3; j++)
                    cout << m[i][j] << "  ";
                    }


But the output is: 7 8 6 0 0 0 0 0 0


Why ??

#2
fayyazlodhi

fayyazlodhi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 403 posts
Replace () with {}. Array indexes are accessed by braces. There is no meaning of parenthesis there.



vector<int> v;

v.push_back(0);

v.push_back(1);

v.push_back(2);

v.push_back(3);

v.push_back(4);

v.push_back(5);

v.push_back(6);

v.push_back(7);

v.push_back(8);



int m[3][3] = { {v[0], v[1], v[2]},

             {v[3], v[4], v[5]},

             {v[6], v[7], v[8]}};


for(int i=0; i<3; i++){

            for(int j=0; j<3; j++)

                    cout << m[i][j] << "  ";

                    }



Today is the first day of the rest of my life




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users