How to Delete Duplicate entries from STL containers?

16 04 2009


If you want to remove duplicate items, you can go for stl::set. But what to do if you want to delete duplicate data from other containers?

removeduplicate
Picture Courtesy – Squidoo


You can use std::unique() algorithm to remove adjacent duplicate items. So at first, sort your data, then call std::unique(). Now all the duplicate data will be rearranged to end of container. Now delete the unwanted range of duplicate data. Have a look at code snippet below.

#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char* argv[])
{
    // Election list.
    vector<string> ElectionList;
    ElectionList.push_back( "Sam" );
    ElectionList.push_back( "John" );
    ElectionList.push_back( "Ron" );
    ElectionList.push_back( "Sam" );
    ElectionList.push_back( "John" );

    // Sort the list to make same items be together.
    sort( ElectionList.begin(), ElectionList.end());

    // Rearrange unique items to front.
    vector<string>::iterator Itr = unique(
        ElectionList.begin(),
        ElectionList.end());

    // Delete the duplicate range.
    ElectionList.erase( Itr, ElectionList.end());
}


Take care that std::unique() just removes the adjacent duplicate entries. It wont remove the entire duplicate entries present in the container. That’s why we need to sort the container at first, which will arrange all duplicate entries to adjacent  locations. 😉


Targeted Audience – Beginners.





How to measure Performance by using High Resolution Timer in Visual C++?

31 03 2009


Ever had a performance tweaking project? The first thing you need is a high resolution stop watch to measure performance of different code blocks. But is there a high resolution stop watch?

highperformancetimer


You can use QueryPerformanceCounter(). You can get the performance counter frequency – i.e. ticks per second by calling QueryPerformanceFrequency(). Have a look at the sample CStopWatch class.

// Stop watch class.
class CStopWatch
{
public:
    // Constructor.
    CStopWatch()
    {
        // Ticks per second.
        QueryPerformanceFrequency( &liPerfFreq );
    }

    // Start counter.
    void Start()
    {
        liStart.QuadPart = 0;
        QueryPerformanceCounter( &liStart );
    }

    // Stop counter.
    void Stop()
    {
        liEnd.QuadPart = 0;
        QueryPerformanceCounter( &liEnd );
    }

    // Get duration.
    long double GetDuration()
    {
        return ( liEnd.QuadPart - liStart.QuadPart) /
                long double( liPerfFreq.QuadPart );
    }

private:
    LARGE_INTEGER liStart;
    LARGE_INTEGER liEnd;
    LARGE_INTEGER liPerfFreq;
};

int main()
{
    // Stop watch object.
    CStopWatch timer;

    // Start timer.
    timer.Start();

    // ZZzzzzz... for few seconds.
    Sleep( 3000 );
    timer.Stop();

    // Get the duration. Duration is in seconds.
    long double duration = timer.GetDuration();

    return 0;
}


Even if the sample app slept for 3 seconds, in high resolution timer, the duration is 2.9xxx seconds. 😉 Can you guess why?


Targeted Audiance – Intermediate.





How to Set Console Text Color?

29 03 2009


Getting bored with the black and white console? Did you ever wish to change the text or background color of console?

setconsoletextcolor
Image Courtesy – reginadowntown.


Yes! You can use the api – SetConsoleTextAttribute(). See the code snippet below.

// Set text color as Yellow with white background.
SetConsoleTextAttribute(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    FOREGROUND_INTENSITY              | // Set Text color
    FOREGROUND_RED | FOREGROUND_GREEN | // Text color as Yellow.
    BACKGROUND_INTENSITY              | // Set Background color
    BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE ); // White Bg.


Please note that you can mix red/green/blue constants to make new colors. Have fun. 🙂


Targeted Audience – Beginners.





How to Pass Array by Reference?

15 03 2009


We used to use arrays, a lot. But did you ever tried how to pass array by reference to another function? Yes. Its a bit tricky.

arraybyreference


Receiving arrays by reference have special syntax. The arrayname and & symbol should be enclosed in parenthesis. And you should specify the size of array. Have a look at the following code snippet.

// Receive Array by reference.
void GetArray( int (&Array) [10] )
{
}

// Test array by reference.
void CRabbitDlgDlg::TestArray()
{
    // Pass array by reference.
    int Array[10] = { 0 };
    GetArray( Array );
}


Indeed, you can pass the array as pointer and then use it. But if you ever need to pass an array by reference, then remember this tip.


Targeted Audience – Beginners.





How to set Font for Static Text Controls?

4 03 2009


By default, static text is displayed in normal fonts. And you don’t have any option to make it bold or italic or underline. Is there any way to enable these styles and change the font of the static text control?

staticfont


Yes! you can do it. First you’ve to get the current font of the text control and then enable the styles you need then set it back. Setting font is done in OnInitDialog() and new font is kept as member variable. See the code snippet below.

BOOL CStaticFontDlg::OnInitDialog()
{
	...

    // Get current font.
    CFont* pFont = GetDlgItem( IDC_STATIC_ITALIC )->GetFont();
    LOGFONT LogFont = { 0 };
    pFont->GetLogFont( &LogFont );

    // Create new font with underline style.
    LogFont.lfUnderline = TRUE;
    m_StaticFont.CreateFontIndirect( &LogFont );

	// Sets the new font back to static text.
    GetDlgItem( IDC_STATIC_ITALIC )->SetFont( &m_StaticFont );

	return TRUE;
}

Now the static text will look like this.

staticfont3


Don’t forget to change the Id of static text control from IDC_STATIC to something else. Or else GetDlgItem() will return invalid handle.


Targeted Audiance – Intermediate.





How to Delete Pointers in Vector or Map in Single Line?

2 03 2009


If you have two or three STL containers which holds pointers in your class as members, then I’m sure that its destructor will be the worst readable one. For deallocating STL containers, we have to iterate through each container by for loop, then delete it. But is there any single line function call to delete all pointers in vector or map, just like chopping the top of a tray of eggs at once? 😉

deletestlcontainers
Picture Courtesy – elitalice.com


You can use for_each() and functors to achieve this. Check out the code snippet.

1) How to delete Vector of pointers in single line

// Necessary headers.
#include "functional"
#include "vector"
#include "algorithm"

using namespace std;

// Functor for deleting pointers in vector.
template<class T>
struct DeleteVectorFntor
{
    // Overloaded () operator.
    // This will be called by for_each() function.
    bool operator()(T x) const
    {
        // Delete pointer.
        delete x;
        return true;
    }
};

// Test Function.
void TestVectorDeletion()
{
    // Add 10 string to vector.
    vector<CString*> StringVector;
    for( int Index = 0; Index < 10; ++Index )
    {
        StringVector.push_back( new CString("Hello"));
    }

    // Now delete the vector in a single  line.
    for_each( StringVector.begin(),
              StringVector.end(),
              DeleteVectorFntor<CString*>());
}

1) How to delete Map of pointers in single line

// Necessary headers.
#include "functional"
#include "map"
#include "algorithm"

using namespace std;

// Functor for deleting pointers in map.
template<class A, class B>
struct DeleteMapFntor
{
    // Overloaded () operator.
    // This will be called by for_each() function.
    bool operator()(pair<A,B> x) const
    {
        // Assuming the second item of map is to be
        // deleted. Change as you wish.
        delete x.second;
        return true;
    }
};

// Test function.
void TestMapDeletion()
{
    // Add 10 string to map.
    map<int,CString*> StringMap;
    for( int Idx = 0; Idx < 10; ++Idx )
    {
        StringMap[Idx] = new CString("Hello");
    }

    // Now delete the map in a single  line.
    for_each( StringMap.begin(),
              StringMap.end(),
              DeleteMapFntor<int,CString*>());
}


STL is really a powerful toolkit. Isn’t it?


Targeted Audience – Intermediate.





gotoxy() function in Visual C++?

1 03 2009


I often feel nostalgic about the gotoxy() function in old Turbo C++. The gotoxy() is used to “jump” to any point of the console screen. I used that function to create nice menu effects. But unfortunately in visual C++, gotoxy() is not available. But is there any other api which can be used instead of gotoxy()?

gotoxy1


You can use SetConsoleCursorPosition(). Check out the following sample program. It reads an integer in loop and prints the time in the right hand corner of console. Just a demonstration of Visual C++’s gotoxy().

gotoxy2

#include "iostream"
#include "time.h"
#include "windows.h"

using namespace std;

// Set current cursor position.
void GotoXY( HANDLE StdOut, SHORT x, SHORT y )
{
    // Set the cursor position.
    COORD Cord;
    Cord.X = x;
    Cord.Y = y;
    SetConsoleCursorPosition( StdOut, Cord );
}

// Print time at the upper right corner of console.
void PrintTime()
{
    // Get handle to console output buffer.
    HANDLE hStdout = GetStdHandle( STD_OUTPUT_HANDLE );  

    // Get current screen information.
    CONSOLE_SCREEN_BUFFER_INFO ScreenBufferInfo = { 0 };
    GetConsoleScreenBufferInfo( hStdout, &ScreenBufferInfo ); 

    // Set the cursor position to upper-right of console.
    GotoXY( hStdout, 50, 0 );

    // Get time and display it.
    time_t tim=time(NULL);
    char *s=ctime(&tim);
    cout << s; 

    // Reset cursor back to position.
    GotoXY( hStdout,
            ScreenBufferInfo.dwCursorPosition.X,
            ScreenBufferInfo.dwCursorPosition.Y );
} 

void main(int argc, char* argv[])
{
    // Just to provide enough space.
    cout << endl << endl; 

    while( true )
    {
        // Print the time.
        PrintTime(); 

        // Read a value.
        int a;
        cout << "Enter number: ";
        cin >> a;
    }
}


Yes! After a short break, I’m back. 🙂 You’ll soon have a happy news from me, within a week. 😉 Keep watching.


Targeted Audience – Beginners.