Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > Data Structures and Algorithm Analysis in C++ Code Examples

Implementation for deterministic skip list

/* Implementation for deterministic skip list */ #include "DSL.h" /** * Construct the tree. * inf is the largest Comparable * and is used to signal failed finds. */ template <class Comparable> DSL<Comparable>::DSL( const Comparable & inf ) : INFINITY( inf ) { bottom = new SkipNode<Comparable>( ); bottom->right = bottom->down = bottom; tail = new SkipNode<Comparable>( INFINITY ); tail->right = tail; header = new SkipNode<Comparable>( INFINITY, tail, bottom ); } /** * Copy constructor. * Left as an exercise. */ template <class Comparable> DSL<Comparable>::DSL( const DSL<Comparable> & rhs ) : INFINITY( rhs.INFINITY) { cout << "Copy constructor is unimplemented" << endl; } /** * Destructor. */ template <class Comparable> DSL<Comparable>::~DSL( ) { makeEmpty( ); delete header; delete tail; delete bottom; } /** * Insert item x into the DSL. */ template <class Comparable> void DSL<Comparable>::insert( const Comparable & x ) { SkipNode<Comparable> *current = header; bottom->element = x; while( current != bottom ) { while( current->element < x ) current = current->right; // If gap size is 3 or at bottom level and // must insert, then promote middle element if( current->down->right->right->element < current->element ) { current->right = new SkipNode<Comparable>( current->element, current->right, current->down->right->right ); current->element = current->down->right->element; } else current = current->down; } // Raise height of DSL if necessary if( header->right != tail ) header = new SkipNode<Comparable>( INFINITY, tail, header ); } /** * Remove item x from the DSL. Unimplemented. */ template <class Comparable> void DSL<Comparable>::remove( const Comparable & x ) { cout << "Sorry, remove unimplemented; " << x << " still present" << endl; } /** * Find the smallest item in the tree. * Return smallest item or INFINITY if empty. */ template <class Comparable> const Comparable & DSL<Comparable>::findMin( ) const { if( isEmpty( ) ) return INFINITY; SkipNode<Comparable> *current = header; while( current->down != bottom ) current = current->down; return elementAt( current ); } /** * Find the largest item in the tree. * Return the largest item or INFINITY if empty. */ template <class Comparable> const Comparable & DSL<Comparable>::findMax( ) const { if( isEmpty( ) ) return INFINITY; SkipNode<Comparable> *current = header; for( ; ; ) if( current->right->right != tail ) current = current->right; else if( current->down != bottom ) current = current->down; else return elementAt( current ); } /** * Find item x in the tree. * Return the matching item or INFINITY if not found. */ template <class Comparable> const Comparable & DSL<Comparable>::find( const Comparable & x ) const { SkipNode<Comparable> *current = header; bottom->element = x; for( ; ; ) if( x < current->element ) current = current->down; else if( current->element < x ) current = current->right; else return elementAt( current ); } /** * Make the tree logically empty. */ template <class Comparable> void DSL<Comparable>::makeEmpty( ) { reclaimMemory( header ); header->right = tail; header->down = bottom; } /** * Test if the tree is logically empty. * Return true if empty, false otherwise. */ template <class Comparable> bool DSL<Comparable>::isEmpty( ) const { return header->right == tail && header->down == bottom; } /** * Internal method to get element field from node t. * Return the element field or INFINITY if t is at the bottom. */ template <class Comparable> const Comparable & DSL<Comparable>:: elementAt( SkipNode<Comparable> *t ) const { if( t == bottom ) return INFINITY; else return t->element; } /** * Print the DSL. */ template <class Comparable> void DSL<Comparable>::printList( ) const { SkipNode<Comparable> *current = header; while( current->down != bottom ) current = current->down; while( current->right != tail ) { cout << current->element << endl; current = current->right; } } /** * Deep copy. Left as an exercise */ template <class Comparable> const DSL<Comparable> & DSL<Comparable>::operator=( const DSL<Comparable> & rhs ) { if( this != &rhs ) cout << "Sorry, operator= is unimplemented" << endl; return *this; } /** * reclaimMemory is left as an exercise. * Hint: delete from top level to bottom level. */ template <class Comparable> void DSL<Comparable>::reclaimMemory( SkipNode<Comparable> *t ) const { if( t != bottom ) cout << "reclaimMemory is unimplemented -- leaking!" << endl; }

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types. It is similar to the class that holds different types of data. A structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types.

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer. In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++: • It can be used to pass current object as a parameter to another method. • It can be used to refer current class instance variable. • It can be used to declare indexers. To understand 'this' pointer, it is important to know how objects look at functions and data members of a class.

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration. T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T.

Return the smallest. Returns the smallest of a and b. If both are equivalent, a is returned. min() function is a library function of algorithm header, it is used to find the smallest value from given two values, it accepts two values and returns the smallest value and if both the values are the same it returns the first value. The versions for initializer lists (3) return the smallest of all the elements in the list. Returning the first of them if these are more than one. The function uses operator< (or comp, if provided) to compare the values.

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values. Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration.

Deallocate storage space. Default deallocation functions (single-object form). A delete operator is used to deallocate memory space that is dynamically created using the new operator, calloc and malloc() function, etc., at the run time of a program in C++ language. In other words, a delete operator is used to release array and non-array (pointer) objects from the heap, which the new operator dynamically allocates to put variables on heap memory. We can use either the delete operator or delete [ ] operator in our program to delete the deallocated space. A delete operator has a void return type, and hence, it does not return a value.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:

Allocate storage space. Default allocation functions (single-object form). A new operator is used to create the object while a delete operator is used to delete the object. When the object is created by using the new operator, then the object will exist until we explicitly use the delete operator to delete the object. Therefore, we can say that the lifetime of the object is not related to the block structure of the program.

A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object. Destructors in C++ are members functions in a class that delete an object. They are called when the class object goes out of scope such as when the function ends, the program ends, a delete variable is called etc. Destructors are different from normal member functions as they don't take any argument and don't return anything. Also, destructors have the same name as their class and their name is preceded by a tilde(~).

The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type. You should see a pointer as a symbolic representation of a memory address. With pointers, programs can simulate call-by-reference. They can also create and manipulate dynamic data structures. In C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed by another variable.

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

In 'C++ program', user is asked to enter three numbers. Then program finds out the largest number among three numbers and displays it with proper message. Program can be used in


To 'reverse a string' in C++ programming, ask to the user to 'enter a string', make a variable say temp of char type "start Swapping". Place First Character of the String in temp and Last




We have already seen user-defined function, the example we have given at the beginning of this tutorial is an example of user-defined function. The functions that we declare and

Internal method to test if a positive number is prime. Not efficient algorithm. Using Internal method to return a prime number at least as large as n. Assumes "n > 0". Insert item x into


Divide the range into equal parts and assign a 'bucket' to each part. Split the data and insert them into the Corresponding bucket by using insertion sort. 'Merge' all the buckets into one

For example reverse of 849 is 948. This code is write using for loop, 'Modulus Operator', if condition statement. User enter any number. 'Receive integer' value from user. Then check