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++ > Beginners Lab Assignments Code Examples

A generic stack class

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
/* A generic stack class */ #include <iostream> #include <new> #include <string> #include <sstream> using namespace std; #if !defined __STACK_H #define __STACK_H namespace stk{ template<class T> class Stack; // Forward declaration of Stack class for overloaded << operator template<class T> ostream& operator<<(ostream &,Stack<T> &); // template declaration of << operator template<class T> class Stack{ private: T *p; int top,length; string str()const; public: Stack(); Stack(const int); Stack(const Stack<T>&); ~Stack(); void push(T); T pop(); int get_length()const; bool is_empty()const; Stack<T> operator=(const Stack<T>&); // only for basic types friend ostream& operator<< <>(ostream&,Stack<T> &); class StackException{ private: string desc; public: StackException(string exp){ desc="Exception : "+exp; } string get_exp(){ return desc; } }; }; template<class T> Stack<T>::Stack(){ top=-1; length=0; p=0; } template<class T> Stack<T>::Stack(const int size){ top=-1; length=size; try{ p=new T[length]; }catch(bad_alloc ba){ cout<<"Memory can not be alllocated "; return; } } template<class T> Stack<T>::Stack(const Stack<T> &o){ top=o.top; length=o.length; try{ p=new T[length]; }catch(bad_alloc ba){ cout<<"Memory allocation failed "; return; } for(int i=0;i<length;i++) p[i]=o.p[i]; } template<class T> Stack<T>::~Stack(){ if(p!=0) delete [] p; } template<class T> void Stack<T>::push(T elem){ if(p==0){ try{ p=new T[1]; }catch(bad_alloc ba){ throw StackException("Memory fault "); } length++; top++; p[top]=elem; } else if(top==(length-1)){ T *q; try{ q=new T[length+1]; }catch(bad_alloc ba1){ throw StackException("Memory fault "); } for(int i=0;i<length;i++) q[i]=p[i]; length++; top++; q[top]=elem; delete [] p; p=q; } else{ top++; p[top]=elem; } } template<class T> T Stack<T>::pop(){ if(p==0 || top==-1){ throw StackException("Stack empty! "); } T ret=p[top]; top--; length--; if(top==-1){ delete [] p; p=0; } else{ T *q; try{ q=new T[length]; }catch(bad_alloc ba){ throw StackException("Memory fault "); } for(int i=0;i<length;i++) q[i]=p[i]; delete [] p; p=q; } return ret; } template<class T> int Stack<T>::get_length()const{ return length; } template<class T> bool Stack<T>::is_empty()const{ return ((p==0)? true : false); } template<class T> string Stack<T>::str()const{ // private member function if(p==0) return string(""); stringstream ss; for(int i=0;i<length;i++){ ss << p[i]; if(i!=(length-1)) ss << ", "; } //ss<<" "; return ss.str(); } template<class T> Stack<T> Stack<T>::operator=(const Stack<T> &stk){ length=stk.length; top=stk.top; if(p!=0) delete [] p; try{ p=new T[length]; }catch(bad_alloc ba){ throw StackException("Memory fault in copying! "); } for(int i=0;i<length;i++) p[i]=stk.p[i]; return *this; } template<class T> ostream& operator<<(ostream &o,Stack<T> &s){ o<<s.str(); return o; } } // namespace stk; #endif

LIFO stack. Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container. stacks are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.

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(~).

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.

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:

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.

In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. • Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.

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.

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.

Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.

Insert element. Inserts a new element at the top of the stack, above its current top element. The content of this new element is initialized to a copy of val. This member function effectively calls the member function push_back of the underlying container object. C++ Stack push () function is used for adding new elements at the top of the stack. If we have an array of type stack and by using the push() function we can insert new elements in the stack. The elements are inserted at the top of the stack. The element which is inserted most initially is deleted at the end and vice versa as stacks follow LIFO principle.

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.

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.

The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. If a function is defined as a friend function in C++ programming language, then the protected and private data of a class can be accessed using the function. By using the keyword friend compiler knows the given function is a friend function. For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.

The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

Access next element. Returns a reference to the top element in the stack. stack::top() function is an inbuilt function in C++ STL, which is defined in <stack> header file. top() is used to access the element at the top of the stack container. In a stack, the top element is the element that is inserted at the last or most recently inserted element. Since stacks are last-in first-out containers, the top element is the last element inserted into the stack. This member function effectively calls member back of the underlying container object. No parameter is required.

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.

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.

#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.

Exception thrown on failure allocating memory. Type of the exceptions thrown by the standard definitions of operator new and operator new[] when they fail to allocate the requested storage space. This class is derived from exception. See the exception class for the member definitions of standard exceptions. Its member what returns a null-terminated character sequence identifying the exception.

Compute exponential function. Returns the base-e exponential function of x, which is e raised to the power x: ex. This function is defined in <cmath> header file. Additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations. This function is also overloaded in <complex> and <valarray> (see complex exp and valarray exp). The function can take any value i.e, positive, negative or zero in its parameter and returns result in int, double or float or long double. Function returns exponential value of x.

When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception (throw an error). An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw. The try and catch keywords come in pairs:

The stringstream, ostringstream, and istringstream objects are used for input and output to a string. They behave in a manner similar to fstream, ofstream and ifstream objects. The function str() can be used in two ways. First, it can be used to get a copy of the string that is being manipulated by the current stream string. This is most useful with output strings. The first form (1) returns a string object with a copy of the current contents of the stream. The second form (2) sets s as the contents of the stream, discarding any previous contents. The object preserves its open mode: if this includes ios_base::ate, the writing position is moved to the end of the new sequence. Internally, the function calls the str member of its internal string buffer object.

In the C++ Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions. The syntax for creating a constant using #define in the C++ is: #define token value

Return length of string. Returns the length of the string, in terms of bytes. This function is used to find the length of the string in terms of bytes. This is the actual number of bytes that conform the contents of the string , which is not necessarily equal to the storage capacity. This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity. Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8).



It is an improvement in BST by adding 2 more key functions - 'rank()' and 'select()'. The time complexity of Order-Statistic tree generation is O(n+n*log(n)). Once the tree is constructed



Program which take Two Strings as input and concatenate Two Strings without using string class function "strcat()". There are total three strings, two for 'input' and third for our Result


The "positive numbers" 1, 2, 3... are known as natural numbers. The program below takes a 'positive integer' from the user and calculates the sum up to the given number. You can find

C++ Program to get all the unique partitions of an integer such that addition of a partition results an integer. An integer n, generate all "possible unique" ways to represent n as sum