jeudi 17 août 2017

What is the correct way to use vectors in functions in C++?

I'm trying to solve this problem http://ift.tt/2fOiN2Z using vectors instead of normal arrays to practice STL but every time I run the code it says Runtime Error! I don't know if I'm not calling the function properly or what!

#include <bits/stdc++.h>

using namespace std;

vector<int> stones;
vector<int> sum;
vector<int> sortedStones;

int cumSum(int l, int r, vector<int> stones){
    for(int i = 0; i < (int) stones.size(); i++){
        if(i == 0)
           sum[i] += stones[i];
        else sum[i] += stones[i] + sum[i-1];
}
    if(l == 0)
        return sum[r];
    else return sum[r] - sum[l-1];
}
int main(){
    int n, x, m, l, r, type, sumType2 = 0;
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> x;
        stones.push_back(x);
        sortedStones.push_back(x);
    }
    sort(sortedStones.begin(), sortedStones.end());
    cin >> m;
    for(int i = 0; i < m; i++){
        cin >> type >> l >> r;
        if(type == 1)  
            cout << cumSum(l, r, stones) <<endl;
        else if(type == 2){
            while(l <= r){
                sumType2 += sortedStones[l];
                l++;
            }
            cout << sumType2 << endl;
        }
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire