我写了以下内容来解决以下问题“给定一个未排序的数字列表,你能找到它们之间绝对差最小的数字吗?如果有多个对,把它们都找出来。”
这是代码
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int* smallestDiff(vector<int> a,int &noOfPairs)
{
sort(a.begin(),a.end());
int * arr = new int(a.size()* sizeof(int) *2);
bool bfoundDiff = false;
int smallestDiff =0;
int num1,num2;
for(size_t i=0;i<a.size()-1;i++)
{
num1 = a[i];
num2 = a[i+1];
int newDiff = num2-num1;
if(!bfoundDiff || newDiff < smallestDiff)
{
smallestDiff = newDiff;
arr[0] = num1;
arr[1]= num2;
noOfPairs = 1;
bfoundDiff = true;
}
}
for(size_t i=0;i<a.size()-1;i++)
{
num1 = a[i];
num2 = a[i+1];
int newDiff = num2-num1;
if(newDiff == smallestDiff && num1!=arr[0] && num2!=arr[1])
{
arr[noOfPairs*2] = num1;
arr[noOfPairs*2 + 1] = num2;
++noOfPairs;
}
}
return arr;
}
int main() {
int _a_size;
cin >> _a_size;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
vector<int> _a;
int _a_item;
for(int _a_i=0; _a_i<_a_size; _a_i++) {
cin >> _a_item;
_a.push_back(_a_item);
}
int noOfPairs=0;
int *result =smallestDiff(_a,noOfPairs);
int noOfelems = noOfPairs*2;
for(int i=0;i<noOfelems;++i)
{
cout<< *(result+i)<<" ";
}
return 0;
}
现在程序按照逻辑运行良好,但在尝试打印结果值时崩溃。我认为将指针作为返回类型传递没有任何问题。
大家看到这里有什么问题吗?