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++ > Computer Graphics Code Examples

C++ Program to Implement Suffix Tree

/* C++ Program to Implement Suffix Tree This C++ Program demonstrates the implementation of Suffix Tree. */ #include <iostream> #include <cstdlib> #include <cstring> #include <string> using namespace std; typedef unsigned char byte; /* SuffixNode Declaration */ class SuffixNode { public: int depth, begin, end; SuffixNode **children; SuffixNode *parent, *suffixLink; /* Constructor */ SuffixNode(int begin, int end, int depth, SuffixNode *parent) { children = new SuffixNode* [38]; this->begin = begin; this->end = end; this->parent = parent; this->depth = depth; } bool contains(int d) { return depth <= d && d < depth + (end - begin); } }; string alphabet; int alphabetSize; int lcsLength; int lcsBeginIndex; /* Class SuffixTree Declaration */ class SuffixTree { public: /* Funtion to build suffix tree for given text */ SuffixNode *buildSuffixTree(string s) { int n = s.length(); int *a = new int[n]; for (int i = 0; i < n; i++) { a[i] = alphabet.find(s.at(i)); } SuffixNode *root = new SuffixNode(0, 0, 0, NULL); SuffixNode *cn = root; root->suffixLink = root; SuffixNode *needsSuffixLink = NULL; int lastRule = 0; int j = 0; for (int i = -1; i < n - 1; i++) { int cur = a[i + 1]; for (; j <= i + 1; j++) { int curDepth = i + 1 - j; if (lastRule != 3) { if (cn->suffixLink != NULL) cn = cn->suffixLink; else cn = cn->parent->suffixLink; int k = j + cn->depth; while (curDepth > 0 && !cn->contains(curDepth - 1)) { k += cn->end - cn->begin; cn = cn->children[a[k]]; } } if (!cn->contains(curDepth)) { if (needsSuffixLink != NULL) { needsSuffixLink->suffixLink = cn; needsSuffixLink = NULL; } if (cn->children[cur] == NULL) { cn->children[cur] = new SuffixNode(i + 1, n, curDepth, cn); lastRule = 2; } else { cn = cn->children[cur]; lastRule = 3; break; } } else { int end = cn->begin + curDepth - cn->depth; if (a[end] != cur) { SuffixNode *newn = new SuffixNode(cn->begin, end, cn->depth, cn->parent); newn->children[cur] = new SuffixNode(i + 1, n, curDepth, newn); newn->children[a[end]] = cn; cn->parent->children[a[cn->begin]] = newn; if (needsSuffixLink != NULL) needsSuffixLink->suffixLink = newn; cn->begin = end; cn->depth = curDepth; cn->parent = newn; cn = needsSuffixLink = newn; lastRule = 2; } else if (cn->end != n || (cn->begin - cn->depth) < j) { lastRule = 3; break; } else lastRule = 1; } } } root->suffixLink = NULL; return root; } /* Funtion to find longest common substring */ int findLCS(SuffixNode *node, int i1, int i2) { if (node->begin <= i1 && i1 < node->end) return 1; if (node->begin <= i2 && i2 < node->end) return 2; int mask = 0; for (int f = 0; f < alphabetSize; f++) { if (node->children[f] != NULL) { mask |= findLCS(node->children[f], i1, i2); } } if (mask == 3) { int curLength = node->depth + node->end - node->begin; if (lcsLength < curLength) { lcsLength = curLength; lcsBeginIndex = node->begin; } } return mask; } /* Funtion to find longest common substring */ void findLCS(string s1, string s2) { string x = "-"; string y = "#"; string ns1 = s1; string ns2 = s2; string s = s1.append(x.append(s2.append(y))); SuffixNode *root = buildSuffixTree(s); lcsLength = 0; lcsBeginIndex = 0; findLCS(root, ns1.length(), ns1.length() + ns2.length() + 1); bool chk = lcsLength > 0; if (chk) { cout<<"\nLongest substring is "<<s.substr(lcsBeginIndex , lcsLength); cout<<endl; } else { cout<<"No substring found"<<endl; } } }; /* Main */ int main() { alphabet = "abcdefghijklmnopqrstuvwxyz1234567890-#"; alphabetSize = alphabet.length(); string s1,s2; cout<<"Finding longest common substring using suffix trees\n"; cout<<"Enter 1st String: "; cin>>s1; cout<<"Enter 2nd String: "; cin>>s2; SuffixTree st; st.findLCS(s1, s2); return 0; }

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.

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.

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.

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:

As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:

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.

The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster. We have different types of bitwise operators in the C++ programming language. The following is the list of the bitwise operators: Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0. This is one of the most commonly used logical bitwise operators. It is represented by a single ampersand sign (&). Two integer expressions are written on each side of the (&) operator.

Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.

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 cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters.

Get character in string. Returns a reference to the character at position pos in the string. This function is used for accessing individual characters. The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not. The first character in a string is denoted by a value of 0 (not 1).

Generate substring. Returns a newly constructed string object with its value initialized to a copy of a substring of this object. The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first). In C++, std::substr() is a predefined function used for string handling. This function takes two values pos and len as an argument and returns a newly constructed string object with its value initialized to a copy of a sub-string of this object. Copying of string starts from pos and is done till pos+len means [pos, pos+len).

A predefined object of the class called iostream class is used to insert the new line characters while flushing the stream is called endl in C++. This endl is similar to \n which performs the functionality of inserting new line characters but it does not flush the stream whereas endl does the job of inserting the new line characters while flushing the stream. Hence the statement cout<<endl; will be equal to the statement cout<< '\n' << flush; meaning the new line character used along with flush explicitly becomes equivalent to the endl statement in C++.

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.

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

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

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.

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

Append to string. This function is used to extend the string by appending at the end of the current value. Extends the string by appending additional characters at the end of its current value. Append is a special function in the string library of C++ which is used to append string of characters to another string and returns * this operator. This is similar to push_back or += operator, but it allows multiple characters to append at the same time. This means a character array can also be appended but it doesn't allow appending a single character. It also allows to append a specific part of the second string to the first string or defining the number of time a string must be appended. An iterator range is also provided to iterate over the character of strings.

Find content in string. Searches the string for the first occurrence of the sequence specified by its arguments. When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences that include characters before pos. Notice that unlike member find_first_of, whenever more than one character is being searched for, it is not enough that just one of these characters match, but the entire sequence must match. Function returns the position of the first character of the first match. If no matches were found, the function returns string::npos.

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.

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.

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



Start the C++ program. Declare the base class emp. Define and declare the function get() to get the employee details. Declare the derived class salary. "Declare and define" the function


C++ Program demonstrates implementation of "Multiset in STL". "Insert element" into the multiset. "Delete element" from the multiset. "Find element" in a multiset. Count elements

In C++ language, Encapsulation is achieved using access specifiers. In encapsulation we make all member variables private, provide public "functions" which allow user to work