Skip to main content

Simple LinkedList program in C++

· 3 min read

Definition:

A linked list is a data structure that consists of a sequence of data records such that in each record there is a field that contains a reference (i.e., a link) to the next record in the sequence.

#include "stdafx.h"
#include "iostream"
using namespace std;

class LinkList
{
private:
struct Node
{
int data;
Node* link;
}*p;

public:
LinkList();
~LinkList();

void Print(); // Prints the contents of linkedlist
void Append(int num); // Adds a new node at the end of the linkedlist
void Delete(int num); // Deletes the specified node from the linkedlist

void AddatBeg(int num);// Adds a new node at the beginning of the linkedlist
void AddAfter(int c, int num); // Adds a new node after specified number of nodes
int Count(); // Counts number of nodes present in the linkedlist

};

LinkList::LinkList()
{
p = NULL;
}

LinkList::~LinkList()
{
if (p == NULL)
return;

Node* tmp;
while(p != NULL)
{
tmp = p->link ;
delete p;
p = tmp;
}
}

// Prints the contents of linkedlist
void LinkList::Print()
{
if (p == NULL)
{
cout<< "EMPTY";
return;
}

//Traverse
Node* tmp = p;
while(tmp != NULL)
{
cout<data<<endl;
tmp = tmp->link ;
}
}

// Adds a new node at the end of the linkedlist
void LinkList::Append(int num)
{
Node *newNode;

newNode = new Node;
newNode->data = num;
newNode->link = NULL;

if(p == NULL)
{
//create first node
p = newNode;
}
else
{
//Traverse
Node *tmp = p;
while(tmp->link != NULL)
{
tmp = tmp->link;
}

//add node to the end
tmp->link = newNode;
}
}

// Deletes the specified node from the linkedlist
void LinkList::Delete( int num )
{
Node *tmp;

tmp = p;
//If node to be delete is first node
if( tmp->data == num )
{
p = tmp->link;
delete tmp;
return;
}

// traverse list till the last but one node is reached
Node *tmp2 = tmp;
while( tmp!=NULL )
{
if( tmp->data == num )
{
tmp2->link = tmp->link;
delete tmp;
return;
}

tmp2 = tmp;
tmp = tmp->link;
}
cout<< "nElement "<<num<<" not Found." ;
}

// Adds a new node at the beginning of the linkedlist
void LinkList::AddatBeg(int num)
{
Node *tmp;

//add new node
tmp = new Node;
tmp->data = num;
tmp->link = p;
p = tmp;
}

//Adds a new node after specified number of nodes
void LinkList::AddAfter(int c, int num)
{
Node *tmp;
Node *tmp2;
int i;
//Skip to the desired portion
for( i = 0, tmp = p; i
{
tmp = tmp->link;

//if end of linked list is encountered
if(tmp == NULL)
{
cout<<endl<< "There are less than "<<c<<" elements" ;
return;
}
}

//insert new node
tmp2 = new Node;
tmp2->data = num;
tmp2->link = tmp->link;
tmp->link = tmp2;
}

// Counts number of nodes present in the linkedlist
int LinkList::Count()
{
Node *tmp;
int c = 0;

//Traverse the entire Linked List
for (tmp = p; tmp != NULL; tmp = tmp->link)
c++;

return (c);
}

void main()
{
LinkList* pobj = new LinkList();
pobj->Append(11);
pobj->Append(22);
pobj->Append(33);
pobj->Delete(33);
pobj->AddatBeg(44);
pobj->AddAfter(1, 55);
pobj->Print();
cout<<endl<< "no. of elements in linked list="<<pobj->Count()<<endl;

delete pobj;
}

/*
OUTPUT
----------------
44
11
55
22

No. of elements in linked list = 4
*/

'Builder' Design Pattern using simple program

· One min read

Definition:

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Program:

#include "iostream"
using namespace std;

// Builder pattern -- Creational example
class Product
{
private:
char* _parts[10];
int i;

public:
Product()
{
i = 0;
}

void Add(char* part)
{
_parts[i] = part;
i++;
}

void Show()
{
cout<
for(int j = 0; j {
cout<<_parts[j]<BuildPartA();
builder->BuildPartB();
}
};

class ConcreteBuilder1 : public Builder
{
private:
Product _product;

public:
virtual void BuildPartA()
{
_product.Add("PartA");
}

virtual void BuildPartB()
{
_product.Add("PartB");
}

virtual Product GetResult()
{
return _product;
}
};

class ConcreteBuilder2 : public Builder
{
private:
Product _product;

public:
virtual void BuildPartA()
{
_product.Add("PartX");
}

virtual void BuildPartB()
{
_product.Add("PartY");
}

virtual Product GetResult()
{
return _product;
}
};

void main()
{
// Create director and builders
Director director;

ConcreteBuilder1 b1;
ConcreteBuilder2 b2;

Product p1;
Product p2;

// Construct product p1
director.Construct(&amp;b1);
p1 = b1.GetResult();
p1.Show();

// Construct product p2
director.Construct(&amp;b2);
p2 = b2.GetResult();
p2.Show();

getchar();
}

/*
OUT PUT

Product Parts:
PartA
PartB

Product Parts:
PartX
PartY
*/

Simple Queue program in C++

· One min read

Definition:

A Queue is a data structure in which addition of new element takes place at the end called rear of Queue and deletion of existing element takes place at the other end called front of Queue .

Principle:

Queue works on the FIFOFirst In First Out principle

#include "stdafx.h"
#include "iostream"
using namespace std;

#define MAX 10

class Queue
{
private:
int arr[MAX];
int front, rear;

public:
Queue()
{
front = -1;
rear = -1;

}

void Add(int item)
{
if(rear == MAX-1)
{
cout<<endl<< "Queue is full";
return;
}

rear++;
arr[rear] = item;

if( front == -1 )
front = 0;
}

int Delete()
{
if(front == -1)
{
cout<<endl<< "Queue is empty";
return NULL;
}

int data = arr[front];

if( front == rear)
front = rear = -1;
else
front++;

return data;
}
};

int main()
{
Queue q;

q.Add(1);
q.Add(2);
q.Add(3);

int i = q.Delete();
cout<<endl<< "item="" deleted="<<i<<endl;

i = q.Delete();
cout<<endl<< "Item deleted = "<<i<<endl;

return 0;
}

/*
OUTPUT
----------------
Item deleted = 1

Item deleted = 2
*/

How to Expand and Contract a MFC Dialog ?

· 3 min read

This article gives the ability to make MFC dialogs expand or contract. The CExpandContractHelper simplifies the process to  expand or contract MFC Dialog.

Steps to use CExpandContractHelper :

  1. Create Dialog Based application
  2. Place the controls as shown below
  3. Add the CExpandContractHelper.cpp & CExpandContractHelper.h files to the project
  4. Create the in the Dialog class CExpandContractHelper* m_pECH;
CExpandDialogDlg::CExpandDialogDlg(CWnd* pParent =NULL)
: CDialog(CExpandDialogDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
//Step - 1 Create CExpandContractHelper
m_pECH = new CExpandContractHelper(IDC_PIC_START, IDC_PIC_END, this);
}
  1. Call ExpandContract in the OnInitDialog
BOOL CExpandDialogDlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
//Step - 2 Call ExpandContract
m_pECH->ExpandContract((CButton*)GetDlgItem(IDC_BN_EXPAND_CONTRACT));
return TRUE;
}
  1. Call ExpandContract in the button handler OnBnClickedBnExpandContract
void CExpandDialogDlg::OnBnClickedBnExpandContract()
{
//Step - 3 Call ExpandContract
m_pECH->ExpandContract((CButton*)GetDlgItem(IDC_BN_EXPAND_CONTRACT));
}

CExpandContractHelper class

//////////////////////////////////////////////////
// Purpose: To expand or contract a dialog control
//////////////////////////////////////////////////
class CExpandContractHelper
{
public:
CExpandContractHelper(UINT nStart, UINT nEnd, CDialog\* dlg);
~CExpandContractHelper(void);
protected:
// ID of start picture control
UINT m_nStart;
// ID of end picture control
UINT m_nEnd;
CDialog* m_dlg;
CButton* m_pButton;
CString m_sExpand;
CString m_sContract;
public:
void ExpandContract(CButton* pButton);
protected:
BOOL IsExpand();
};

CExpandContractHelper.cpp

#include "StdAfx.h"
#include "ExpandContractHelper.h"
CExpandContractHelper::~CExpandContractHelper(void)
{
}
CExpandContractHelper::CExpandContractHelper(
UINT nStart, // Start Picture control ID
UINT nEnd, // End Picture control ID
CDialog *dlg // Dialog pointer
)
{
m_nStart = nStart;
m_nEnd = nEnd;
m_dlg = dlg;
}
BOOL CExpandContractHelper::IsExpand()
{
// 1 - Load button caption Expand/Contact
m_sExpand = "&amp;Expand >>";
m_sContract = "&lt;&lt; &amp;Contract";
// 2 - Find out if we need to expand or collapse the dialog
CString strCaption;
m_pButton->GetWindowText( strCaption );
BOOL bExpand = ( strCaption == m_sExpand ); // Collapse by default
return bExpand;
}
void CExpandContractHelper::ExpandContract(
CButton* pButton // Expand Contract button pointer
)
{
m_pButton = pButton;
// 3 - Get current dialog window rectangle
CRect rcDialog;
m_dlg->GetWindowRect( &amp;rcDialog );
int nNewHeight = -1;
if( IsExpand() )
{
// 4a - Change Expand/Contract button caption
pButton->SetWindowText( m_sContract );
// 4b - Calculate new dialog height
CWnd* pWndLarge = m_dlg->GetDlgItem( m_nEnd );
ASSERT_VALID( pWndLarge );
CRect rcLarge;
pWndLarge->GetWindowRect( &amp;rcLarge );
nNewHeight = rcLarge.top-rcDialog.top;
}
else
{
// 5a - Change Expand/Contract button caption
pButton->SetWindowText( m_sExpand );
// 5b - Calculate new dialog height
CWnd* pWndSmall = m_dlg->GetDlgItem( m_nStart );
ASSERT_VALID( pWndSmall );
pWndSmall->ShowWindow(FALSE);
CRect rcSmall;
pWndSmall->GetWindowRect( &amp;rcSmall );
nNewHeight = rcSmall.top-rcDialog.top;
}
// 6 - Set new dialog height
ASSERT( nNewHeight > 0 );
m_dlg->SetWindowPos( NULL, 0, 0,
rcDialog.Width(), nNewHeight,
SWP_NOMOVE | SWP_NOZORDER );
// 7 - Set the enabled state for each control depending on whether
// the control is currently visible or not
CWnd* pWndControl = m_dlg->GetWindow( GW_CHILD );
while( pWndControl != NULL )
{
CRect rcControl;
pWndControl->GetWindowRect( &amp;rcControl );
pWndControl->EnableWindow( rcControl.top &lt;= rcDialog.top + nNewHeight );
pWndControl = pWndControl->GetWindow( GW_HWNDNEXT );
}
// 8 - Check if a control still has the focus
// (can lose it if the active control becomes disabled)
CWnd* pWndActiveControl = CWnd::GetFocus();
if( pWndActiveControl == NULL )
{
// 9 - Set focus to "first" control on dialog
CWnd* pWndFirstControl = m_dlg->GetNextDlgTabItem( NULL );
ASSERT_VALID( pWndFirstControl );
ASSERT( pWndFirstControl->IsWindowEnabled() );
pWndFirstControl->SetFocus();
}
}

Tutorial to create MFC ActiveX Control which can be used in HTML Pages

· One min read

Definition: ActiveX controls are COM components which are self-registering and Implements standard interfaces that deal specifically with GUI-based tasks such as rendering, sizing, activation, and property persistence.

An ActiveX control is anything you might see in the Toolbox of Visual studio (i.e. EditBox, combobox e.t.c) we can even use the Activex controls in web pages using and handling events with Javascript.

For complete tutorial Refer ActiveX Control Tutorial

Invoke Native C++ DLL from .NET Code

· One min read

There are 4 Approaches to accomplish this.

Approach

  1. (Explicit) P/Invoke Approach  
  2. Dynamic P/Invoke Approach
  3. Implicit P/Invoke (Use a C++/CLI wrapper) Approach
  4. Convert C++ DLL to a COM server, and call it from .NET code through .NET-COM interop

I don't like to reinvent the wheel so please go through msdn forum answer here

Center an MFC Dialog

· One min read

Use the CWnd::CenterWindow method to center the dialog. Write CenterWindow() method in the OnInitDialog() method.

BOOL CMyDialog::OnInitDialog() { 
CenterWindow();
return TRUE;
}

Creating a CDC from a HDC

· One min read

If we get handle to a DC and sometimes we might want to create a CDC from that. One example is owner-drawn lists, combos, and buttons. we will receive a draw item message with a hDC. The below code can be used to convert hdc into CDC.

 void MyList::DrawItem(LPDRAWITEMSTRUCT lpDrawItem) { 
CDC* pDC;
pDC = CDC:FromHandle(lpDrawItem->hDC);
}

NOTE: This technique for any of the other MFC class/ Windows handle pairs too.