0

I am trying to replace an entire row of a 2d array with another vector. My code is currently as follow:

#include <stdio.h>

int main(){
    int imax = 5;
    int jmax = 5;
    double x[imax][jmax] = {0.0};
    double a[imax] = {1,2,3,4,5};
}   

In other words, now my x is a matrix with 5x5. How do I add/append/rewrite the 1st row of X with my a vector?

Thanks

2
  • Not legal C++. Change the declaration of imax and jmax to const int. Have you studied for loops yet? Commented Sep 29, 2017 at 3:36
  • Yes, I've done for loops. Is there anyway to do this with for loops? Commented Sep 29, 2017 at 3:38

2 Answers 2

1

One way to copy the row "without a loop" is the std::copy standard library algorithm.

std::copy(a, a + imax, x[0]); // x[0] is the first row

The algorithm contains the loop. Depending on the implementation this might emit a single call to memcpy or memmove instead.

Sign up to request clarification or add additional context in comments.

Comments

0

imax and jmax should be const to make that code legal. Anyways, one obvious possibility is to copy elements one by one like this:

for ( int j = 0; j < jmax; j++ ) {
    x[row][j] = a[j];
}

Another way is to use memcpy. That should be faster in normal circumstances, however, you rely on the assumption that the square bracket [] operator was not overloaded. Also you only can overwrite one row this way, not a column, so be careful when and where you use that.

memcpy( x[row], a, sizeof(a) );

('row' is your variable where you put the index of the row you want to replace)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.