向量下标超出c ++中的范围错误

hyt*_*ucx 3 c++ algorithm stl vector

我正在尝试编写一个接受n个整数输入的程序,并找出在给定输入中出现最大次数的程序.我正在尝试运行t案例的程序.为此,我实现了一种类似于算法的计数排序(可能有点过时),它计算输入中每​​个数字的出现次数.如果有多个具有相同最大出现次数的数字,我需要返回其中较小的数字.为此,我实施了排序.
我面临的问题是,每次我在Visual C++上运行程序时,我都会收到一个错误,告诉"向量下标超出范围".在Netbeans下,它产生的返回值为1并退出.请帮我找到问题所在

   #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;
}
Run Code Online (Sandbox Code Playgroud)

Bo *_*son 5

a.clear()向量之后没有任何成员,其大小为0.

添加呼叫以a.resize(n)使其大小合适.您还需要调整大小buff到需要的大小.