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++ > Code Snippets Code Examples

Matching Elements Using the equals and mismatch Operations

/* Matching Elements Using the equals and mismatch Operations */ #include <iostream> #include <vector> #include <algorithm> using namespace std; template<class Container, class Iterator> void ShowElement(Container& c, Iterator& itor); int main() { typedef vector<int>::iterator VectorInterator; vector<int> intValueVector(4); intValueVector[0] = 1; intValueVector[1] = 2; intValueVector[2] = 3; intValueVector[3] = 4; vector<int> intValueVector2(3); intValueVector2[0] = 1; intValueVector2[1] = 2; intValueVector2[2] = 3; VectorInterator first1 = intValueVector.begin(); VectorInterator last1 = intValueVector.end(); VectorInterator first2 = intValueVector2.begin(); if (equal(first1, last1, first2)) cout << "intValueVector == intValueVector2\n"; else cout << "intValueVector != intValueVector2\n"; pair<VectorInterator, VectorInterator> pi = mismatch(first1, last1, first2); cout << "First mismatch element in intValueVector = "; ShowElement(intValueVector, pi.first); cout << "\n"; cout << "First mismatch element in intValueVector2 = "; ShowElement(intValueVector2, pi.second); cout << "\n"; return 0; } template<class Container, class Iterator> void ShowElement(Container& c, Iterator& itor) { if (itor != c.end()) { if (itor != c.begin()) cout << *itor << "\tthe previous element is " << *(itor - 1); else cout << "first"; } else cout << "last"; }

Return iterator to beginning. Returns an iterator pointing to the first element in the vector. Notice that, unlike member vector::front, which returns a reference to the first element, this function returns a random access iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. The C++ function std::vector::begin() returns a random access iterator pointing to the first element of the vector. This function does not accept any parameter.

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.

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 first position where two ranges differ. Compares the elements in the range [first1,last1) with those in the range beginning at first2, and returns the first element of both sequences that does not match. C++ Algorithm mismatch() function compares both the containers to spot for any mismatch of values. The function returns the first element of both the containers that does not match. The elements are compared using operator== (or pred, in version (2)). The function shall not modify any of its arguments. This can either be a function pointer or a function object. Function returns a pair, where its members first and second point to the first element in both sequences that did not compare equal to each other.

In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program. The vector class provides various methods to perform different operations on vectors. Add Elements to a Vector: To add a single element into a vector, we use the push_back() function. It inserts an element into the end of the vector. Access Elements of a Vector: In C++, we use the index number to access the vector elements. Here, we use the at() function to access the element from the specified index.

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

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.

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.

Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result. • Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used.

In C++, pair is defined as a container in a header library <utility> which combines the two data elements having either the same data types or different data types. In general, the pair in C++ is defined as a tuple in Python programming language which also can give the output as a combined result of joining the two items specified by the pair container and it consists of the first element will be first and the second element will be second only it cannot be disturbed in the order or sequence of elements specified and are always accessed by the dot operator followed by the keyword "first" and "second" elements respectively. In C++ the pair is a container in <utility> header and is also a container class in STL (Standard Template Library) which uses "std" namespace so it will be as std::pair template class for demonstrating pair as a tuple.

Relational operators for vector. Performs the appropriate comparison operation between the vector containers lhs and rhs. In C++, relational and logical operators compare two or more operands and return either true or false values. The equality comparison (operator==) is performed by first comparing sizes, and if they match, the elements are compared sequentially using operator==, stopping at the first mismatch (as if using algorithm equal). The less-than comparison (operator<) behaves as if using algorithm lexicographical_compare, which compares the elements sequentially using operator< in a reciprocal manner (i.e., checking both a<b and b<a) and stopping at the first occurrence.

Access element. Returns a reference to the element at position n in the vector container. A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception. Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior. Function returns the element at the specified position in the vector.

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.

Return iterator to end. Returns an iterator referring to the past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced. Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as vector::begin. This function does not accept any parameter.

Test whether the elements in two ranges are equal. Compares the elements in the range [first1,last1) with those in the range beginning at first2, and returns true if all of the elements in both ranges match. C++ Algorithm equal()function compares the elements in both the containers and returns a true value if all the elements in both the containers are found to be matching. The first range is from [first1,last1) and the second starts from first2. The elements are compared using operator== (or pred, in version (2)). The function shall not modify any of its arguments.

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.


In graph theory, an "edge coloring" of a graph is an assignment of colors to the edges of the graph so that no two adjacent edges have the same color. Any "2 edges" connected to same

A "Structure Distance" containing two data members (inch and feet) is declared to store the distance in inch-feet system. Here, two structure variables d1 and d2 are created to






An "Inline Function" is a function upon which the compiler has been requested to perform inline expansion. programmer has requested that the compiler insert the complete body of