vector subscript out of range error in c++

2019-04-12 05:04发布

问题:

I am trying to write a program that takes an input of of n integers, and finds out the one that occurs the maximum number of times in the given input. I am trying to run the program for t cases. For this, I have implemented a counting sort like algorithm (perhaps a bit naiive), that counts the number of occurrences of each number in the input. In case there are multiple numbers with the same maximum occurrence, I need to return the smaller among those. For this, I implemented sorting.
The issue I am facing is, that every time I run the program on Visual C++, I am getting an error that tells "vector subscript out of range". Under Netbeans, it is generating a return value of 1 and exiting. Please help me find the problem

   #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    #include <vector>


using namespace std;

int findmax(vector<int> a, int n)
{
    int i,ret;
    ret = 0;
    for ( i = 0; i <n; i++)
    {
        if (a[i] > ret) {
                ret = a[i]; 
        }
    }
    return ret;
}


int main() {
    int i = 0, j = 0, k = 0, n,m,r1,r2;
    vector<int> a;
    int t;
    vector<int> buff;

    cin>>t;
    while(t--) {

        cin>>n;
        a.clear();
        buff.clear();
        for ( i = 0; i < n; i++) {

            cin>>a[i];
        }

        sort(a.begin(),a.end());
        m = findmax(a,n);
        for ( j = 0; j < m+1; j++) {
            buff[a[j]] = buff[a[j]] + 1;
        }
        k = findmax(buff,m+1);

        for ( i = 0; i < m+1; i++) {
            if (buff[i] == k) {
                 r1 = i;
                 r2 = buff[i];
                 break;
            }
        }

        cout<<r1<<" "<<r2<<endl;
    }
    return 0;
}

回答1:

After a.clear() the vector doesn't have any members, and its size is 0.

Add a call to a.resize(n) to make it the proper size. You also need to resize buff to whatever size it needs to be.



回答2:

This isn't how you populate an array.

cin>>a[i];

You need to use the push_back() method or pre-allocate the appropriate size.



回答3:

The problem is that you're illegally using indexes of your vector that don't exist (you never add any items to the vector). Since you know the size, you can resize it after you clear it:

a.clear();
a.resize(n);
buff.clear();
buff.resize(n);


回答4:

this line it's the culprit:

 cin>>a[i];

you must use push_back:

  cin >> temp;
  a.push_back(temp);

or resize(n) before:

    cin>>n;
    a.resize(n);
    for ( i = 0; i < n; i++) {
        cin>>a[i];
    }

then you should pass you vector by reference to findmax

int findmax(vector<int> &a, int n)
...


回答5:

    for ( i = 0; i < n; i++) {

        cin>>a[i];
    }

will be out of range. The vector, as you construct it, has zero size.