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

The nth element algorithm partitions the sequence [first..last) on the value

The nth element algorithm partitions the sequence [first..last) on the value nth_element Header <algorithm> template<class RandomAccessIterator> inline void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last) The nth_element algorithm partitions the sequence [first..last) on the value referenced by nth. All the elements less than or equal to the value are placed before value and all elements greater than value are placed after value in the sequence. The non-predicate version of nth_element uses operator< for comparisons. template<class RandomAccessIterator, class Compare> inline void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare compare) The nth_element algorithm partitions the sequence [first..last) on the value referenced by nth. All the elements less than or equal to the value are placed before value and all elements greater than value are placed after value in the sequence. The predicate version of nth_element uses the compare function for comparisons. Samples Sample for Non-Predicate Version // disable warning C4786: symbol greater than 255 character, // okay to ignore #pragma warning(disable: 4786) #include <iostream> #include <algorithm> #include <functional> #include <vector> using namespace std ; void main() { const int VECTOR_SIZE = 8 ; // Define a template class vector of int typedef vector<int> IntVector ; //Define an iterator for template class vector of strings typedef IntVector::iterator IntVectorIt ; IntVector Numbers(VECTOR_SIZE) ; IntVectorIt start, end, it ; // Initialize vector Numbers Numbers[0] = 4 ; Numbers[1] = 10; Numbers[2] = 70 ; Numbers[3] = 30 ; Numbers[4] = 10; Numbers[5] = 69 ; Numbers[6] = 96 ; Numbers[7] = 100; start = Numbers.begin() ; // location of first // element of Numbers end = Numbers.end() ; // one past the location // last element of Numbers cout << "Before calling nth_element\n" << endl ; // print content of Numbers cout << "Numbers { " ; for(it = start; it != end; it++) cout << *it << " " ; cout << " }\n" << endl ; // partition the elements by the 4th element nth_element(start, start+4, end) ; cout << "After calling nth_element\n" << endl ; cout << "Numbers { " ; for(it = start; it != end; it++) cout << *it << " " ; cout << " }\n" << endl ; } Program Output Before calling nth_element Numbers { 4 10 70 30 10 69 96 100 } After calling nth_element Numbers { 4 10 10 30 69 70 96 100 } 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 <vector> using namespace std; void main() { const int VECTOR_SIZE = 8 ; // Define a template class vector of int typedef vector<int > IntVector ; //Define an iterator for template class vector of strings typedef IntVector::iterator IntVectorIt ; IntVector Numbers(VECTOR_SIZE) ; IntVectorIt start, end, it ; // Initialize vector Numbers Numbers[0] = 4 ; Numbers[1] = 10; Numbers[2] = 70 ; Numbers[3] = 30 ; Numbers[4] = 10; Numbers[5] = 69 ; Numbers[6] = 96 ; Numbers[7] = 100; start = Numbers.begin() ; // location of first // element of Numbers end = Numbers.end() ; // one past the location // last element of Numbers cout << "Before calling nth_element:\n" << endl ; // print content of Numbers cout << "Numbers { " ; for(it = start; it != end; it++) cout << *it << " " ; cout << " }\n" << endl ; // partition the elements by the 4th element nth_element(start, start+4, end, less<int>()) ; cout << "After calling nth_element:\n" << endl ; cout << "Numbers { " ; for(it = start; it != end; it++) cout << *it << " " ; cout << " }\n" << endl ; } Program Output Before calling nth_element: Numbers { 4 10 70 30 10 69 96 100 } After calling nth_element: Numbers { 4 10 10 30 69 70 96 100 }

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:

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.

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

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.

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

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

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.

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.

Function object class for less-than inequality comparison. Binary function object class whose call returns whether the its first argument compares less than the second (as returned by operator <). 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. This function does not return any value.

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.

Sort element in range. Rearranges the elements in the range [first,last), in such a way that the element at the nth position is the element that would be in that position in a sorted sequence. C++ Algorithm nth_element() function is used to sort the elements between the first and nth element in ascending order and element between nth and last are not sorted. However, no element in between nth and last is smaller than an element between first and nth element. The other elements are left without any specific order, except that none of the elements preceding nth are greater than it, and none of the elements following it are less. The elements are compared using operator< for the first version, and comp for the second.

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.

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.

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.

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.












Test if the tree is logically empty. Return true if empty, false otherwise. Then print the tree contents in 'sorted order'. Internal method to print a subtree t in sorted order. And Internal