We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
B.a[i][j] is not defined at any point since you haven't told your vector how large it will be. You either have to use vector::push_back(), which will increase the size of the vector to accommodate, or assign B.a to a usable length first. There are two easy ways to do the latter. First, just to assign your output to the input or argument from the get-go. You can declare and define 'Matrix B = A;' to assign the whole object, or you can just add line 'B.a = this->a;' to your current code to pass only a. The second and even easier route: you can just pass the argument by value and skip the entire step, since you never have to define Matrix B at all. If you really want, you can also manually resize the vectors to suit your needs:
int sizeOfA = A.a.size();
B.a.resize(sizeOfA);
for(int i=0; i < sizeOfA; i++) {
B.a[i].resize(sizeOfA); }
Obviously, that would be terribly verbose and generally unnecessary, but you can do it and it would also solve your segmentation fault issue. Nevertheless, the strategy nicely demonstrates the nature of your problem. Otherwise, the code works. Had to do a double-take on a[i][j], but that will technically work as well since it defaults to the current object. I personally use this->a[i][j], though.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Operator Overloading
You are viewing a single comment's thread. Return to all comments →
B.a[i][j] is not defined at any point since you haven't told your vector how large it will be. You either have to use vector::push_back(), which will increase the size of the vector to accommodate, or assign B.a to a usable length first. There are two easy ways to do the latter. First, just to assign your output to the input or argument from the get-go. You can declare and define 'Matrix B = A;' to assign the whole object, or you can just add line 'B.a = this->a;' to your current code to pass only a. The second and even easier route: you can just pass the argument by value and skip the entire step, since you never have to define Matrix B at all. If you really want, you can also manually resize the vectors to suit your needs:
Obviously, that would be terribly verbose and generally unnecessary, but you can do it and it would also solve your segmentation fault issue. Nevertheless, the strategy nicely demonstrates the nature of your problem. Otherwise, the code works. Had to do a double-take on a[i][j], but that will technically work as well since it defaults to the current object. I personally use this->a[i][j], though.