0

Can anybody debug this code for me along with brief explanation/tips:

https://code.sololearn.com/cifGlcANxJM6/?ref=app

6th Apr 2020, 9:41 AM
Farzam
Farzam - avatar
6 Réponses
+ 3
vector is defined in the vector header, you didn't include it. Secondly, you cannot simply do this: vector<int> data; data[i] = something. A vector starts out with an array that is empty, so this is the same as trying to access an array out-of-bounds. data.push_back(i) or data.emplace_back(i) is to be used to add new data to the array. Alternatively you can define the size of the internal array of the vector by resizing the array up-front, either by using data.resize( size ) or by defining the size upon construction like vector<int> data( size ).
6th Apr 2020, 10:08 AM
Dennis
Dennis - avatar
+ 5
Dennis 👍 looks like you have figured out it already.. https://code.sololearn.com/cw1wX5upoCvw/?ref=app
6th Apr 2020, 10:42 AM
Aaditya Deshpande
Aaditya Deshpande - avatar
+ 2
You know, the least you could do is indent the code correctly to make it easier on us. Just a tip.
6th Apr 2020, 10:01 AM
Dennis
Dennis - avatar
+ 2
As for tips: I think sum's definition is weird. It returns its argument via pointer in its first argument, why not simply return the value from the function? Returning via pointer should only be reserved for returning arrays or when you really know what you're doing. A vector has a size member function which you could use instead of the second parameter, n. The vector is taken by reference, which means you can write to it, yet, the function does not write to it. I also think you should make the vector const to make it clear that the function does not write to it. Also, use proper parameter names, 'd' doesn't cut it. So, this would make the sum's declaration: int sum( const std::vector<int>& data ); I think you can change the definition accordingly. :) fyi, you can just use std::accumulate ( numeric header ), which does the same thing, but more generally, if it's not for an assignment. ( which it probably is ) You shouldn't define int i; outside the loops like that. This was a very old C style ( C89 ) thing from 30 years ago that you should probably just unlearn. Just do for( int i = 0; i < N; ++i ) instead. Only declare your variables right before you need them, not at the beginning of a function. If you want to go a bit more advanced, set_size should be defined as constexpr int set_size(){ ... } if your compiler supports it. The inline is really unnecessary here. ( and maybe rename it to get_size? ) And also, try to stop using 'using namespace std' if your school doesn't force you to, or at least try not to use it in your personal projects.
6th Apr 2020, 10:17 AM
Dennis
Dennis - avatar
+ 1
Thank you so much Dennis 😊. Loved your explanation. Will follow your tips here onwards.
6th Apr 2020, 12:57 PM
Farzam
Farzam - avatar
+ 1
I also thank Aaditya for modifying the code for me :)
6th Apr 2020, 12:58 PM
Farzam
Farzam - avatar