Kean411
Kean411

Reputation: 3

Extracting Columns From a Vector Matrix to store in an Array

Problem Explanation

Edit: Solution is added to the bottom in case anyone needs it

Let's Say I have a matrix with following data

1 3 2 1 7 9 5 8
9 1 3 8 6 9 4 1
3 2 4 0 4 5 7 4
3 5 6 4 6 5 7 4

I want to define a size_of_chunks variable that will store the number of chunks for example if I set size_of_chunks=2 then the matrix will become

Chunk1 |  Chunk2 | Chunk3 | Chunk4  
-------|---------|--------|------- 
 1 3   |   2 1   |  7 9   |  5 8
 9 1   |   3 8   |  6 9   |  4 1
 3 2   |   4 0   |  4 5   |  7 4
 3 5   |   6 4   |  6 5   |  7 4

I want to take one of these chunks and use push_back to a std::vector<int>temp(row*col);

       Chunk1 |    
     ---------| 
Start-> 1 3   |   
        9 1   |   
        3 2   |   
  End-> 3 5   |   

so the temp will look like the following: temp = {1, 3, 9, 1, 3, 2, 3, 5}

Later on when I did the same steps to chunk 2 the temp will look like this:
temp = {1, 3, 9, 1, 3, 2, 3, 5, 2, 1, 3, 8, 4, 0, 6, 4}

Code

int row = 4;
int col = 8;
int size_of_chunk = 2;
std::vector<int> A(row*col);
std::vector<int> temp(row*col);

// Here a Call for the Function to Fill A with Data

for(int r=0;r<row;r++){
  for(int c=0;c<col;c+=size_of_chunk){
    for(int i=0;i<c;i++){
      temp.push_back(A[r*col+i]);
    }
  }
}

It's giving me values that doesn't match to end results how should I approach this problem ? Thank you!

Solution

for(int c=0;c<col;c+=size_of_chunk){
  for(int r=0;r<row;r++){
    for(int i=0;i<size_of_chunk;i++){
      temp.push_back(A[r*col+i+c]);
    }
  }
}

Upvotes: 0

Views: 92

Answers (1)

john
john

Reputation: 87959

Don't specify a size for the vector in the constructor and use push_back, because that way you end up with a vector twice as big as it should be. Do one or the other.

In this case presumably it should be

std::vector<int> temp;

That is, start the vector at size zero and increase it's size using push_back.

Upvotes: 1

Related Questions