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++ > Visual C++ 5.0 Standard C++ Library Code Examples

Adjacent find algorithm finds consecutive pairs of matching elements in a sequence.

Adjacent find algorithm finds consecutive pairs of matching elements in a sequence. adjacent_find Header <algorithm> template<class ForwardIterator> inline ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last) ; The adjacent_find algorithm finds consecutive pairs of matching elements in a sequence. The adjacent_find algorithm returns an iterator referencing the first consecutive matching element in the range (first, last), or last if there are no such elements. Comparison is done using operator== in this non-predicate version of the algorithm. template<class ForwardIterator, class BinaryPredicate> inline ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred) ; The adjacent_find algorithm finds consecutive pairs of matching elements in a sequence. adjacent_find returns an iterator referencing the first consecutive matching element in the range [first, last), or last if there are no such elements. Comparison is done using the binary_pred function in this version of the algorithm. The binary_pred function can be any user-defined function. You could also use one of the binary function objects provided by STL. Samples Sample for Non-Predicate Version // disable warning C4786: symbol greater than 255 character, // okay to ignore #pragma warning(disable: 4786) #include <algorithm> #include <iostream> using namespace std; void main() { const int ARRAY_SIZE = 8 ; int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ; int *location ; // stores the position for the first pair // of matching consecutive elements. int i ; // print content of IntArray cout << "IntArray { " ; for(i = 0; i < ARRAY_SIZE; i++) cout << IntArray[i] << ", " ; cout << " }" << endl ; // Find the first pair of matching consecutive elements // in the range [first, last + 1) // This version performs matching using operator== location = adjacent_find(IntArray, IntArray + ARRAY_SIZE) ; //print the matching consecutive elements if any were found if (location != IntArray + ARRAY_SIZE) // matching consecutive // elements found cout << "Found adjacent pair of matching elements: (" << *location << ", " << *(location + 1) << "), " << "at location " << location - IntArray << endl; else // no matching consecutive elements were found cout << "No adjacent pair of matching elements were found" << endl ; } Program Output IntArray { 1, 2, 3, 4, 4, 5, 6, 7, } Found adjacent pair of matching elements: (4, 4), at location 3 Sample for Predicate Version // disable warning C4786: symbol greater than 255 character, // okay to ignore #pragma warning(disable: 4786) #include <iostream> #include <algorithm> #include <functional> #include <string> #include <vector> using namespace std; void main() { const int VECTOR_SIZE = 5 ; // Define a template class vector of strings typedef vector<string > StringVector ; //Define an iterator for template class vector of strings typedef StringVector::iterator StringVectorIt ; StringVector NamesVect(VECTOR_SIZE) ; //vector containing names StringVectorIt location ; // stores the position for the // first pair of matching // consecutive elements. StringVectorIt start, end, it ; // Initialize vector NamesVect NamesVect[0] = "Aladdin" ; NamesVect[1] = "Jasmine" ; NamesVect[2] = "Mickey" ; NamesVect[3] = "Minnie" ; NamesVect[4] = "Goofy" ; start = NamesVect.begin() ; // location of first // element of NamesVect end = NamesVect.end() ; // one past the location // last element of NamesVect // print content of NamesVect cout << "NamesVect { " ; for(it = start; it != end; it++) cout << *it << ", " ; cout << " }\n" << endl ; // Find the first name that is lexicographically greater // than the following name in the range [first, last + 1). // This version performs matching using binary predicate // function greater<string> location = adjacent_find(start, end, greater<string>()) ; // print the first pair of strings such that the first name is // lexicographically greater than the second. if (location != end) cout << "(" << *location << ", " << *(location + 1) << ")" << " the first pair of strings in NamesVect such that\n" << "the first name is lexicographically greater than" << "the second\n" << endl ; else cout << "No consecutive pair of strings found such that\n" << "the first name is lexicographically greater than " << "the second\n" << endl ; } Program Output NamesVect { Aladdin, Jasmine, Mickey, Minnie, Goofy, } (Minnie, Goofy) the first pair of strings in NamesVect such that the first name is lexicographically greater than the second

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.

The function in C++ language is also known as procedure or subroutine in other programming languages. To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability. Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check... Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them:

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.

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

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.

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.

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.

Find equal adjacent elements in range. Searches the range [first,last) for the first occurrence of two consecutive elements that match, and returns an iterator to the first of these two elements, or last if no such pair is found. The C++ function std::algorithm::adjacent_find() finds the first occurrence of two consecutive elements that are identical and returns an iterator pointing to the first element if identical element exists consecutively otherwise returns an iterator pointing to the last element. Two elements match if they compare equal using operator== (or using pred, in version (2)). Function returns an iterator to the first element of the first pair of matching consecutive elements in the range [first,last).

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.

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

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

Function object class for greater-than inequality comparison. Binary function object class whose call returns whether the its first argument compares greater than the second (as returned by operator >). The std::greater is a functional object which is used for performing comparisons. It is defined as a Function object class for the greater-than inequality comparison. This can be used for changing the functionality of the given function. This can also be used with various standard algorithms such as sort, priority queue, etc. Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a function call.

Inline function is one of the important feature of C++. So, let's first understand why inline functions are used and what is the purpose of inline function? When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

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.







You will learn to convert "binary number" to octal, and octal number to binary manually by creating a "user-defined" function. In this, first convert the binary number to "decimal".




The object should calculate the 'total area' & the volume based on the side measurement. If the program supplies a side equal or lower than 0, reset the side to 1. "Create an empty"

"Array index" starts with 0, which means the first array element is at index 0, second is at index 1 and so on. We use this information to display the array elements. See the C++ code