Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
    int arr[10];
    arr[0] = 1;
    arr[1] = 2;
    // sorting array
    sort(arr,arr+10);

    // printing array
    for(int i=0;i<10;i++)
    {
        cout<<arr[i]<<endl;
    }
    return 0;
}




the output is like this:
-1212121212121
-1212121212121
-1212121212121
-1212121212121
-1212121212121
-1212121212121
-1212121212121
1
2




what i want:

1
2




how can i do this
Posted

Sorting the array will NEVER return 1,2. It has 10 members. What values do the other members hold? Use your debugger to find out.

The array only has only two members initiallised and you sort the whole array. The other values of the array are unknown. They need to be set to something.

C#
int arr[10] = {0,0,0,0,0,0,0,0,0,0};

arr[0] = 1;
arr[1] = 2;


You may choose to sort only the first 2 (or initialised members) - you must then only display that subsection of the array not the whole 10 members. That will then give 1,2.

[Edit]
1. Yes you must set all values to known values - you can use a for loop or memset().

2. You can as I said sort a subset of your array - you must then only display those sorted values not the whole array.
 
Share this answer
 
v4
Comments
bhawin parkeria 19-May-15 1:31am    
ok , just one more thing , how about if i have an array of 100000 int

do i have to initialize each index

wont it be clumpsy

and also how about
sort(arr,arr+2);
[no name] 19-May-15 1:39am    
See edit
Shmuel Zang 19-May-15 2:01am    
5'ed.
To set all items to a default known value, just change from
Quote:
int arr[10];
to
C++
int arr[10] = {0}; // init ALL the array items with value 0


Note the C++11 standard provides uniform initializers, the array container and ranged for loop:
C++
#include<iostream>
#include <array>
#include<algorithm>

using namespace std;

int main()
{
    array <int,10> arr{0}; // this initializes all the items with 0
    arr[0] = 1;
    arr[1] = 2;
    // sorting array
    sort(arr.begin(),arr.end());

    for ( auto  x : arr)
    {
      cout << x << endl;
    }
}
 
Share this answer
 
Comments
[no name] 19-May-15 4:33am    
Apparently this also works (empty initializer):
array ‹int,10› arr{};
http://stackoverflow.com/questions/18295302/default-initialization-of-stdarray
CPallini 19-May-15 4:52am    
True!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900