关于c++数组与vector的区别

emm,第一次写博客有点紧张。
今天刷蓝桥杯碰到一个小问题,有一个测试点总是过不去,后来把代码里的数组换成vector向量后就解决了。题目是这样的:
给定一个序列,每次询问序列中第l个数到第r个数中第K大的数是哪个。
输入格式
第一行包含一个数n,表示序列长度。
第二行包含n个正整数,表示给定的序列。
第三个包含一个正整数m,表示询问个数。
接下来m行,每行三个数l,r,K,表示询问序列从左往右第l个数到第r个数中,从大往小第K大的数是哪个。序列元素从1开始标号。
输出格式
总共输出m行,每行一个数,表示询问的答案。
样例输入
5
1 2 3 4 5
2
1 5 2
2 3 2
样例输出
4
2

下面是我开始用数组写的代码:

#include <iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b){
	return a>b; 
}
int main() {
    int n;
    cin>>n;
    int a[n];       //这里定义数组
    for(int i=0;i<n;i++){
    	cin>>a[i];
	}
    int m;
    cin>>m;
    int result[m];   //又定义了一个数组
    for(int i=0;i<m;i++){
		int l,r,k;
    	cin>>l>>r>>k;
    	int *temp=new int [n];
        for(int j = 0; j < n; j++) {
            temp[j] = a[j];
        }
        sort(temp + l - 1, temp + r, cmp);
        result[i] = temp[l - 1 + k - 1]; 
		delete [] temp;       
	}
	for(int i=0;i<m;i++){
		cout<<result[i]<<endl;
	}
    return 0;
}

本来以为很完美了,但是问题是总是有那么一个测试点过不去,而且我也没法查看测试数据,很难受,后来我将数组换成向量试了下:

#include <iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool cmp(int a,int b){
	return a>b; 
}
int main() {
    int n;
    cin>>n;
    vector<int> a(n);   //诺,就是这里,我把它换成了向量
    for(int i=0;i<n;i++){
    	cin>>a[i];
	}
    int m;
    cin>>m;
    vector<int> result(m);    //这里也换一下
    for(int i=0;i<m;i++){
		int l,r,k;
    	cin>>l>>r>>k;
    	int *temp=new int [n];  
        for(int j = 0; j < n; j++) {
            temp[j] = a[j];
        }
        sort(temp + l - 1, temp + r, cmp);
        result[i] = temp[l - 1 + k - 1]; 
		delete [] temp;       
	}
	for(int i=0;i<m;i++){
		cout<<result[i]<<endl;
	}
    return 0;
}

居然测试成功了,百思不得其解。。。。。。
百度一下!!!!
原因见下篇博客。

猜你喜欢

转载自blog.csdn.net/qq_37747797/article/details/84188967
今日推荐