Skip to main content

Posts

Selection Sort (C++ way) for vector of any type

In my last article have seen how we can leverage C++ STL to do selection sort on the vector of integers only. However, the selection sort wasn't very generic to accept vectors of any basic type and sort accordingly. The below program was an effort to make the same selection sort (ascending order) implementation for vectors of any type like vectors of integers, doubles, chars, etc. #include < iostream > #include < algorithm > #include < vector > template < class ForwardIterator1, class ForwardIterator2 > void iters_swap (ForwardIterator1 a, ForwardIterator2 b) {     std::swap (*a, *b); } template < typename T > void selectionSort(std::vector< T > &v) { // Selection sort typedef typename std::vector ::value_type vt; typename std::vector ::iterator it = v.begin(); while(it != v.end()) {     typename std::vector ::iterator i_Min = std::min_element (it, v.end()); iters_swap(i_Min, it); ++it; } } int main() {

Selection Sort (C++ Way)

Selection Sort using Standard Template Libraries (not C++ 11): Selection sort works by finding smallest element from the list unsorted list, swap with leftmost element and proceed until all the elements are in order. Selecting the lowest element requires scanning all n elements (this takes n − 1 comparisons) and then swapping it into the first position. Finding the next lowest element requires scanning the remaining n − 1 elements and so on. Hence the complexity is  O(N^2) . The C++ implementation is like below: #include < iostream > #include < algorithm > #include < vector > template < class ForwardIterator1, class ForwardIterator2 > void iters_swap (ForwardIterator1 a, ForwardIterator2 b) {      std::swap (*a, *b); } template < typename T > void selectionSort(T &v) { // Selection sort std::vector ::iterator it = v.begin(); while(it != v.end()) {         std::vector ::iterator i_Min = std::min_element(it,

An Amazing recursion results in crash

A scenario, as per C++ specification supported and also supported by the GNU C++ compiler but not right to do so. Example: The following piece of code works both in the GNU C++ compiler as well as Microsoft C++ compiler. Code execution gives the right result (I mean expected output). #include  < vector > #include < iostream > class Simple { public: Simple(unsigned int aInt) : memberInteger(aInt) { } void Amaze() { myVector = { Simple(1), Simple(2) }; } unsigned int memberInteger; std::vector < Simple > myVector; }; int main() { Simple s(0); s.Amaze(); size_t sz = s.myVector.size(); return 0; } The size of my vector returns 2. Now, I've changed the a code little bit and it gets compiled well in Gnu C++ compiler(4.9.2 and used "g++ -std=c++11 -Wall Simple_Defeat.cpp -o Simple_Defeat" to compile) but not in Microsoft C++ compiler (Checked with 2013): #include < vector > #include < iostream &g

Programming: Windows Threading Vs Linux Threading (Part 6)

A thread cleanup handler in Linux and Windows thread cancellation: A cleanup handler is a measure, used to deallocate a resource only if the thread exits or canceled. To register a cleanup handler, need to call pthread_cleanup_push() and pass a pointer to cleanup function and the void * argument. The pthread_cleanup_pop() function removes the routine at the top of the calling thread's cancellation cleanup stack and optionally invokes it (if execute is non-zero). The following sample code shows how a dynamically allocated buffer from a thread can be deallocated on canceling the thread in Linux. #include < pthread.h > #include < stdio.h > #include < string.h > #include < unistd.h >  char *pgArray = 0; /* Buffer allocation */ char * allocate_array (size_t size) {     return new char[size]; } void release_array (void *pArg) {     if(pgArray)     {         printf("release_array() called..\n");         delete []pgArray;     }

Programming: Windows Threading Vs Linux Threading (Part 5)

Thread Cancellation in GNU/Linux : Today, I'm interested to explore how we can prepare thread in GNU/Linux to ignore thread cancellation. This is acvhieved with pthread_setcancelstate(). The signature of the function is: int pthread_setcancelstate(int state, int *oldstate);  The function is thread and signal safe. The function sets the cancel  state to one of PTHREAD_CANCEL_ENABLE or  PTHREAD_CANCEL_DISABLE and returns the old cancel state. Please see the second parameter. void *Print_Details(void *param) {      printf("This is secondary thread's entry...\n");      int oldState;      pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldState);      sleep(1);      for(int i = 0; i < 10; ++i)      {           printf("Inside the secondary thread...\n");      }      pthread_setcancelstate(oldState, NULL);      printf("This is secondary thread's exit...\n");      return NULL; } /* Main program */ int main() {      pt

Programming: Windows Threading Vs. Linux Threading (Part 4)

Thread Cancellation is a way where it's necessary sometimes to terminate a thread explicitly from another thread. In Windows we have a Function, it's TerminateThread() The function signature : BOOL WINAPI TerminateThread(   _Inout_  HANDLE hThread,   _In_     DWORD dwExitCode ); This function is always asynchronous. It never guarantees that the thread will always terminate by the time the function returns. This function never cleans up a stack of destroyed threads. So, it's not recommended to use this function until it's absolutely necessary. Note : As mentioned by Jeffrey Richter, Microsoft designed this API purposely implemented this way to terminate thread(s). This ensures that other threads are still running and accessing the terminated threads stack will not get an access violation. So, by leaving the terminated threads stack in memory, other threads which are accessing the stack of the killed thread can continue to execute. In Linux we have a function, i

Programming: Windows Threading Vs Linux Threading (Part 3)

Continued from Part 2: In Linux, normally (when we use default pthread_attribute , aka sending null to pthread_create()), we're creating the  joinable thread . There is another type of thread named detached thread , which We'll see later. A joinable thread is like a process, isn't automatically cleaned up by GNU/Linux when it terminates. Instead, its exit states hang around the system (like a zombie process) until the thread called pthread_join() obtains its return value. Let's see what happens in the Windows world: When the thread terminates (the normal way, aka the thread function returns), it ensures the following : 1. All C++ objects created in the thread function will be destroyed properly via their destructor. 2. The OS will clean up memory owned by the thread's stack. 3. The system will decrement threads kernel objects usage count. The following code snippet (GNU/Linux) shows a thread created using pthread_create() with default pthread_attr_t