How To Sort An Array

The same sort function used to sort STL vector can be used for sorting arrays also. Surprised? Sometimes life is easier than we expect. 

using namespace std;

int main()
   int MyArray[] = {10, 9, 8, 7, 6};
   sort(MyArray, MyArray + 5);
   for (int i = 0; i < 5; ++i)    {       cout << MyArray[i] <<'\n';    }    return 0; } [/sourcecode]


2 Responses to How To Sort An Array

  1. teambob says:

    You might like to go into more detail on how this works i.e. iterators

    Otherwise a number of people may copy+paste it without knowing what is going on.

  2. cppkid says:

    The sort function works on addresses of containers. Normally we pass the starting object iterator and the ending object iterator + 1 (the end of the vector). An iterator is nothing but an address. We employ the same strategy here.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: