Nameless King - 1 year ago 50
C++ Question

# 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);
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;
}
``````

So this is a C++ program that is meant to identify the largest and smallest number in a user-inputted array. Code::Blocks 16, C++0X standards.
In its current state, however, when I input
`1 2 3 4 5`
for the array, the program's output is as following:

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

What is the problem here? I am an amateur coder and am probably making some dumb mistakes I didn't notice. :P

Your biggest issue here is that

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

doesn't construct the vector you think it does. `p[0]` and `p[N-1]` are `floats`, not pointers. So what you do is construct a vector with `p[0]` number of elements all with the value of `p[N-1]`. What you need if you want to construct a `vector` for an array is

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

You also have an issue with

``````m=vec[N];
``````

Since `N` is the size of the vector `vec[N]` is not a valid element. It is one past the end. What you need is

``````m=vec[N - 1];
``````

Do note that the vector is not needed here at all. You can just take a `float*` in `yourFunction` and sort that directly. That would look liked

``````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);
Even though you said you cannot change the code in `main` I would also like to let you know that `new` should be preferred over `malloc`