std::sort

Having
 
int numbers[]={1,2,3,4,5};

can I directly invoke std::sort to sort this array, or do I have to copy these values to some std container (like vector) and then sort the container?
You can use std::sort directly by doing:
std::sort(numbers, numbers+sizeof(numbers)/sizeof(int);
or with C++11:
std::sort(std::begin(numbers), std::end(numbers); //C++11
will sort all elements in numbers.

If you want to sort just the middle 3 elements (2,3,4) then do:
std::sort(numbers+1, numbers+4);
std::sort:
http://www.cplusplus.com/reference/algorithm/sort/

Note the default call:
template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);


template allows you to call the function with any data type. See this for more info:
http://www.cplusplus.com/doc/tutorial/templates/

The word "any" isn't quite right for this example, note: class RandomAccessIterator

This means that the function is expecting a type that can be treated as a random access iterator:
http://www.cplusplus.com/reference/iterator/RandomAccessIterator/

It doesn't have to be a random access iterator!. The only thing is that whatever data type you send it needs to be able to handle the "valid expressions" that a random access iterator can handle.

If you have:
int arr[] = { 1, 2, 3, 4 };

then "arr" is a pointer. Pointers can handle all of the "valid expressions" that a random access iterator requires, so arr ( and arr + n ) are valid arguments to pass to std::sort.

Topic archived. No new replies allowed.