Sort in C ++ does not show the correct input value

4

I made a code to read 3 values, and with sort() it sorts the values in ascending order and just below shows the input values. For example: -14 21 7 it orders right but output shows -14 7 21 // 21 21 7 being that it was to be -14 7 21.

#include <iostream>
#include<algorithm>

using namespace std;

int numero[2],ent[2];

int main(){

    cin>>ent[0];
    cin>>ent[1];
    cin>>ent[2];
    numero[0]=ent[0];
    numero[1]=ent[1];
    numero[2]=ent[2];

    sort(numero,numero+3);


    cout<<numero[0]<<endl<<numero[1]<<endl<<numero[2]<<endl;
    cout<<endl<<ent[0]<<endl<<ent[1]<<endl<<ent[2]<<endl;

    return 0;
}
    
asked by anonymous 19.08.2018 / 04:05

1 answer

5

There is an important semantic difference between [2] using in two different places. Syntax is something that can be repeated with a different meaning. It's like a "take it to me" and "this is light to me".

In the first line of effective code you are declaring two variables, meaning you are telling the compiler to reserve space for two variables , one that will be called in the code ahead of numero and the other of ent . You are saying that the placeholder should be considered the size of the type that supports a int and that it needs exactly 2 memory locations that fits this type in each of the variables, so it is an array , a vector .

Below we use the variable name syntax with the same [2] , but now also with [0] , [1] . Now, if I accessed index 0, and 1, and 2, I am accessing 3 different indexes, 3 elements of this array . But I booked 2! There is a problem there.

If the first element is 0, as the mathematics teaches us, the second is 1, to have an element 2 we need to have 3 elements. So the variable declaration is wrong, there needs to be [3] . It may sound weird, but it makes perfect sense.

If I tell you to count to 9 starting with the first known positive integer in math, you count 10 numbers.

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Count on it, there's 10.

I made the code better:

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

int main() {
    int numero[3], ent[3];
    cin >> ent[0];
    cin >> ent[1];
    cin >> ent[2];
    sort(numero, numero + 3);
    cout << numero[0] << ", " << numero[1] << ", " << numero[2] << endl ;
    cout << ent[0] << ", " << ent[1] << ", " << ent[2];
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

One last note is that you do not usually use array of C in C ++. For this you have better structures: Difference between std :: list, std :: vector and std :: array .

    
19.08.2018 / 18:16