C++ 排序函数中的奇怪之处

Oddities in a C++ sorting function

#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <vector>
using namespace std;

// To Do: Finish this function
void yourFunction(int N, vector<float>&vec, float &m, float &n){
sort(vec.begin(), vec.end());
n=vec[0];
m=vec[N];
}

int main()
{
    int N;
    float m,n;
    cout << "Please enter the length of array." << endl;
    cin >> N;
    float *p = (float*) malloc(sizeof(float)*N);
    cout << "Please enter the numbers in your array.";
    for(int i=0;i<N;i++)
        cin >> *(p+i);
    vector<float>vec(p[0],p[N-1]);
    yourFunction(N,vec,m,n);
    cout << "The largest number in your array is " << m << endl;
    cout << "The smallest number in your array is " << n << endl;
    return 0;
}

所以这是一个 C++ 程序,用于识别用户输入的数组中的最大和最小数字。 Code::Blocks16、C++0X标准。 但是,在当前状态下,当我为数组输入 1 2 3 4 5 时,程序的输出如下:

https://i.stack.imgur.com/phktl.png

这里有什么问题?我是一名业余编码员,可能会犯一些我没有注意到的愚蠢错误。 :P

首先你的向量创建是错误的。

vector<float>vec(p[0],p[N-1]);//p[0] and p[N-1] are values.You need address range

vector<float>vec(p,p+N); //begin with P(including) and end with p+N(excluding)

然后,

n=vec[0];
m=vec[N];  //Last element at N-1
}

应该是

m = vec[N-1];

还有为什么你有数组和向量。

要么使用

std::sort(p,p+N); //and get rid of the vector

或直接将值放入向量中。

vector<float> vec(N);
for(int i=0;i<N;i++)
   cin>>vec[i];

你最大的问题是

vector<float>vec(p[0],p[N-1]);

没有构建您认为可以构建的向量。 p[0]p[N-1]floats,不是指针。所以你要做的是构造一个向量,其中包含 p[0] 个元素,所有元素的值都为 p[N-1]。如果你想为一个数组构造一个vector,你需要的是

vector<float>vec(p,p + N);

您也遇到了

的问题
m=vec[N];

由于 N 是向量的大小 vec[N] 不是有效元素。这是一个过去的结局。你需要的是

m=vec[N - 1];

请注意,此处根本不需要向量。您可以只在 yourFunction 中取一个 float* 并直接对其进行排序。那看起来会很喜欢

void yourFunction(int N, float* data, float &m, float &n){
    std::sort(data, data + N);
    n = data[0];
    m = data[N - 1];
}

int main()
{
    int N;
    float m,n;
    cout << "Please enter the length of array." << endl;
    cin >> N;
    float *p = (float*) malloc(sizeof(float)*N);
    cout << "Please enter the numbers in your array.";
    for(int i=0;i<N;i++)
        cin >> *(p+i);
    yourFunction(N,p,m,n);
    cout << "The largest number in your array is " << m << endl;
    cout << "The smallest number in your array is " << n << endl;
    return 0;
}

即使您说您不能更改 main 中的代码,我也想让您知道 new 应该优于 malloc