Gold mine of Visual C++ tricks!
How to sort an array by using STL?
![]()
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.
| Print article | This entry was posted by Jijo Raj on August 10, 2008 at 2:08 pm, and is filed under C++. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 1 year ago
please help me about the codes of sorting by using array…..
about 1 year ago
Please help me,,,,i want your opinion about sorting
in c++ by using array….thanks..may god bless you all…mwaaaahhh!!!chup chup..chup…