C++ syntax question for prefix sum

So I just finished reading Silver > Prefix Sums, and I understand the concept. But I’m a little confused regarding the syntax of c++. Below is the Guide’s code for reference:

#include <bits/stdc++.h>
using namespace std;
#define sz(x) (int)size(x)

using ll = long long;
using vl = vector<ll>;

vl psum(const vl& a) {
    vl psum(sz(a)+1); 
    for (int i = 0; i < sz(a); ++i)
        psum[i+1] = psum[i]+a[i];
    // or partial_sum(begin(a),end(a),begin(psum)+1);
    return psum;

int main() {
    for (ll i: psum({1,2,3,4,5}))
        cout << i << " ";
    // 0 1 3 6 10 15
  1. Can you please explain what the “vl” part of “vl psum” method header means. I’m assuming vl is used to state that the method is returning a vector, but not 100% sure.
  2. Can you please explain why the method input has a & in it. I’ve seen this & before in other c++ code, but I don’t understand why you use the &.

Thanks for your help!

  1. Yeah, that means that the method returns a vector<long> vector<long long>. (boy i hate macros) EDIT: ben pointed out that typedef’s aren’t macros, but i just don’t like the essence of those things

  2. The & means that the function takes a reference. IIRC C++ parameters are always copied, and this stops C++ from going through the trouble of making a whole copy of the vector just to create a prefix sum array.

1 Like
  1. It actually means vector<long long> LOL, and it is used to prevent overflow because if the array maximum was like 10^9, then it could overflow.

  2. This basically enables you to change your array inside the function. Let’s say you make your partial sum array to be a[i] = a[i-1] + a[i] in the psum function. Inside the main function, as well as other functions, this array “a” would be the partial sum array if that function was ever called. If that explanation was ambiguous, then check out this link: Calling a reference variable inside a function.

1 Like

Type aliases are not macros.