How to sort an array by using STL?

10 08 2008

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.

Advertisements




How to watch a range of values inside huge array?

3 07 2008


Assume you’ve an array with 1000 elements in it and you want to watch elements from 500 ~ 510, what will you do? One method is you can watch the array directly which will list all the 1000 variables and you’ve to scroll up to 500th element and have to watch. Is there any trick to watch just the range of 10 elements between 500 to 510?


Yes! Basically the idea is, you’ve to add – (Array+RangeStart)+RangeCount to the watch window. But there are different scenarios and obviously the trick varies slightly. See examples below.

1) If you have dynamically allocated array.
Check the code snippet.

// Array ptr with 1000 elements.
int* pArray = new int[1000];

// Initialize range 500 to 509 as 1.
for( int ArrayIndex = 500; ArrayIndex < 510; ++ArrayIndex )
{
    pArray[ ArrayIndex ] = 1;
}

In this case for watching range 500 ~ 510, you’ve to add – (pArray+500),10 to watch window. See the screenshot.

2) If you have array on stack.
If you’re array is on stack, if you add your array to watch window, the debugger automatically expands all elements, since it knows the max size of array. But we just want to see the range. See the code snippet.

// Array with 1000 elements.
int Array[1000] = { 0 };

// Initialize range 500 to 509 as 1.
for( int ArrayIndex = 500; ArrayIndex < 510; ++ArrayIndex )
{
    Array[ ArrayIndex ] = 1;
}

In this case for watching range 500 ~ 510, you’ve to add – ((int*)Array+500),10 to watch window. See the screenshot.


Watch window is a Treasure chest! isn’t it? 😉


Targeted Audience – Intermediate.