Pages

Sunday, June 5, 2016

Sorting in C++

sort method defined under algorithm header file can be used to sort arrays and vectors.
#include

1. Sorting char and int array:

The input parameters to sort char and integer array are pointers to beginning and end of array.


char mychar[] = {'z','q','-','e','a'};
int length = sizeof(mychar)/sizeof(char);
sort(mychar, mychar+length);

int myint[] = {'100','34','45','23','12'};
int length = sizeof(mychar)/sizeof(int);
sort(mychar, mychar+length);

It can also be used to sort strings defined as character arrays.

char mychar[] = "back";
int length = sizeof(mychar)/sizeof(char);
sort(mychar, mychar+length);

The output will be "abck"

2. Sorting vectors:

Similar to arrays, vectors can be sorted using sort method by passing pointers to begin and end of vector.

vector<int> myvector = {'z','q','-','e','a'};
sort(myvector.begin(),myvector.end());

Return value of the method is void as it alerts the containers or arrays directly through pointers.

No comments:

Post a Comment