Using Quick Sort Function with MFC CArray class

 

Today a person asked, how to use existing sort function of Visual C Runtime library with MFC CArray object. It’s pretty interesting. STL and CRT has implemented some best piece of code for sorting. So you don’t have to burn you brain cell again to implement a sort functionality for your MFC collection classes like CArray and it’s derivatives like CStringArray (should be an object implemented sequential storage. In my understanding CList is not well suited for this).

So how can you do that? See the sample below. Check the comments as well to understand the implementation.

 

// Typedef of comparison prototypes
typedef int (__cdecl *GENERIC_COMPARE_FXN) ( const void * elem1, const void * elem2 );
typedef int (__cdecl *STRING_COMPARE_FXN )( const CString * elem1, const CString * elem2);

// Class derived from CArray or it's derivatives
class CSortableStringArray : public CStringArray
{
public:
	void Sort(STRING_COMPARE_FXN pfnCompare = Compare);

protected:
	static int __cdecl Compare(const CString * pstr1, const CString * pstr2);
};

/*
 * Implement your own compare function for your class.
 * can be either static or global
 */
int CSortableStringArray::Compare(const CString * pstr1, const CString * pstr2)
{
	int nRet = 0;
	if( pstr1 && pstr2 )
		nRet = pstr1->Compare ( *pstr2 ); // Use CompareNoCase for case insensitive comparison
	return nRet;
}

/*
 * Sort Function
 */
void CSortableStringArray::Sort( STRING_COMPARE_FXN pfnCompare)
{
	CString * pcsInternalStr = GetData();
	// Call quick sort function
	qsort( pcsInternalStr, // pointer to string
		   GetSize(),sizeof(CString), // number and size of elements
		   (GENERIC_COMPARE_FXN)pfnCompare // routine for comparison
		  );
	// You can define your own routine which accepts two pointers(should be)
	// and typecast it to GENERIC_COMPARE_FXN when passing to qsort
}

OK here’s a peice of code to test your class

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		_tprintf(_T("Fatal Error: MFC initialization failed\n"));
		nRetCode = 1;
	}
	else
	{
		srand( (unsigned)time( NULL ) ); // Generate seed for rand().
		CSortableStringArray arr;
		CString str;
		for (int i=0; i< 1000;i++)
		{
			str.Format( _T("%6d"), rand());// Get a random number string.
			arr.Add(str);
			_tcprintf( _T("%s\n"), (LPCTSTR)str);
		}
		long ltim=GetTickCount();
		arr.Sort();
		for (int i=0; i< 1000;i++)
		{
			_tcprintf( _T("%s\n"), (LPCTSTR)arr[i]);
		}
	}

	return nRetCode;
}

The code is compiled and verfied under Visual C++ 2008. You can implement your own class derived from CArray to implement the sort functionality like this. The only thing you've to do is that, the apt comparison routine must be provided with the type of CArray object being instantiated. This can be either static or global.

 

MSDN has a KB article on this. Please check

Technorati Tags: ,,,,

Sharing my thoughts...

 

Protect your account using GMail's Remote sign-out

 

Here’s a story which happened during my travel. On my way back from Japan, I had stop at Singapore Changi Airport, I was eager to check my mail and also I had to inform my close friends that I reached Singapore safely. I managed to find a hub for Internet browsing (due to some credential issues, my laptop was unable to connect to the wireless service out there),  and I typed “Gmail.com” on the browser. Unfortunately I was using the sessions, which was being used by someone else who forgot to logoff from his remaining time. Quickly the GMail was opened with someone else’s account. May be he forgot to was forgot to log off from his mail, or so.Whatever the be the reason the stranger’s mailbox was directly opened to me. I never wished to do anything fraud, so I signed out quickly and logged into my account after logging off the current browsing session(10 minutes or something is the time offered by them for free browsing per session).

imageOften we use our mail account for storing lot of personal stuffs other than e-mails like Credit card information, bank account number, some people even storing passwords in that. So if someone hijacked your mail account, it’s like missing your privacy, effort and time(sometimes your money if you kept your account information in that). In many cases, the the unwanted “Remember Me” check box will be always set. This dangerous especially when you’re using a public computer. The other case is that, if you’re using a tabbed browser, when you close the “tab” of your mail, not necessarily closes the current session. As we all know we can login again without the giving the credentials again.

Today only I noticed a useful information in the bottom of my Gmail Page. That my current IP address and the time of last login etc. I thought of sharing it with you and when I started writing this blog post, I realized that GMail blog communicated their new feature in their latest blog post

Anyway here I’m completing my blog post on that. You can sign into GMail from different machines and you can also keep valid sessions in the other mostly used computers with “Remember Me” option or something. This can also be misused by someone else, if he manage to get into your valid E-mail session. What could be the solution to sign him out?

Unlike Google Talk, Yahoo messenger doesn’t allow us to sign in multiple machines to keep our privacy. It’s nice to hear that Google is at most concerned about our privacy to flexibly control our account activities in multiple machines. What if you can remotely sign-out from all of your valid login sessions from the remote computers? Cool no? GMail introduced some cool new features like, recent activity, Remote sign-out features to enhance your privacy. You can get the link to this from the bottom of your Google Mail.

image

(Image courtesy GMail Blog)

Recent activity includes any times that your mail was accessed, using a regular web browser, through a POP client, from a mobile device, etc. GMail will list the IP address from which the access was made, as well as the time and date.

Currently I’m not really logged into multiple sessions in my GMail account, hence I am taking the original image posted in GMail blog.

image

Multiple sessions opened in GMail. Image courtesy GMail Blog

You can get detailed information from GMail Help on this feature. Enjoy your privacy!!!

 

Sharing my thoughts...

 

Multi-thread debugging facilities in Visual Studio 2008

 

Visual Studio 2008 provides some smart features for debugging multi-threaded programs. Let’s take a look to few features

image

Flag

You can flag interesting threads from the list

Category

Provides type of a thread, like worker thread or Main thread.

Name

This is one of the coolest feature. You can name a thread. It’s gives flexible way to identify the threads in a readable way.  As you see in the first picture, you can give any crappy name for your threads :)

Location

Provides information on the thread start function. When the mouse is over the location, it also shows up the current stack frame of the particular thread where the mouse belongs.

image

Switch To Thread

You can switch to any running thread within the application using “Switch To Thread” feature. The acitve thread will be marked with a yellow arrow as you see in the first figure.

Show Thread In Source

This feature provides gives an indicator on which are the source statements are currently being executed by different threads. In a single point, there could be multiple threads. By hovering the mouse over this location, you can see the current threads which executes the particular line. In the picture below, you can see multiple squiggly marks. Again, these are the lines currently dealt with different threads. You can also see the tool tip which gives information on multiple threads executing the particular statement.

image

Suspend

The thread Debug window also provides the suspend count of the threads running in the system

Debug Location Bar

This bar provides more information on the current debug location of multiple threads. You can choose a running thread from the “Thread” combo box. If you check the “Stack Frame”, you can see the call stack of the particular thread selected. On selecting a thread, it acts as “Switch To Thread” as I described above.

image

Next Statement Location

Finally it shows, a green indicator which indicates the next statement when the thread returns from the current function being executed.

image

Sharing my thoughts...