Posts tagged C++ sort()
How to sort an array by using STL?
2![]()
Today I’ll tell a story… Its interesting!
Once upon a time, there lived a C++ Padawan. One day, he want to sort an array. He knows that STL have std::sort() function. But he want to sort an array, not an STL container. What a fool he is? Native array’s don’t have iterators. So how could he call the std::sort() function? Well, he is clever – he created a vector, copied his array to vector, then he called the sort() function. After sorting, he copied the data back to array.
The End!

But now he is ashamed of what he did. Because now he realize that he can use std::sort() directly on native array too! But how?
![]()
You can use array pointers direclty in STL algorithms. They act like iterators itself. Have a look at the code snippet.
// Integer array with 10 items.
int Array[10] = { 9,3,2,4,0,6,7,8,1,5 };
// Sort them.
std::sort( Array, Array + 10 );
![]()
Well, Can you guess – who was that C++ trainee? It was me.
![]()
Targeted Audience – Beginners.