C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
The merge algorithm merges two sorted sequences: [first1..last1) and [first2..last2)
The merge algorithm merges two sorted sequences: [first1..last1) and [first2..last2)
merge
Header
<algorithm>
template<class InputIterator1, class InputIterator2, class OutputIterator> inline
OutputIterator merge( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result )
The merge algorithm merges two sorted sequences: [first1..last1) and [first2..last2) into a single sorted sequence starting at result. This version assumes that the ranges [first1..last1) and [first2..last2) are sorted using operator<. If both ranges contain equal values, the value from the first range will be stored first. The result of merging overlapping ranges is undefined.
template<class InputIterator1, class InputIterator2, class OutputIterator, class Compare> inline
OutputIterator merge( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare compare )
The merge algorithm merges two sorted sequences: [first1..last1) and [first2..last2) into a single sorted sequence starting at result. This version assumes that the ranges [first1..last1) and [first2..last2) are sorted using the compare function. If both ranges contain equal values, the value from the first range will be stored first. The result of merging overlapping ranges is undefined.
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 <vector>
#include <list>
#include <deque>
using namespace std ;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of ints
typedef IntVector::iterator IntVectorIt ;
IntVector NumbersVector(MAX_ELEMENTS) ;
IntVectorIt startv, endv, itv ;
// Define a template class list of int
typedef list<int> IntList ;
//Define an iterator for template class list of ints
typedef IntList::iterator IntListIt ;
IntList NumbersList ;
IntListIt first, last, itl ;
// Define a template class deque of int
typedef deque<int> IntDeque ;
//Define an iterator for template class deque of ints
typedef IntDeque::iterator IntDequeIt ;
IntDeque NumbersDeque(2 * MAX_ELEMENTS) ;
IntDequeIt itd ;
// Initialize vector NumbersVector
NumbersVector[0] = 4 ;
NumbersVector[1] = 10;
NumbersVector[2] = 70 ;
NumbersVector[3] = 10 ;
NumbersVector[4] = 30 ;
NumbersVector[5] = 69 ;
NumbersVector[6] = 96 ;
NumbersVector[7] = 100;
startv = NumbersVector.begin() ; // location of first
// element of NumbersVector
endv = NumbersVector.end() ; // one past the location
// last element of NumbersVector
// sort NumbersVector, merge requires the sequences
// to be sorted
sort(startv, endv) ;
// print content of NumbersVector
cout << "NumbersVector { " ;
for(itv = startv; itv != endv; itv++)
cout << *itv << " " ;
cout << " }\n" << endl ;
// Initialize vector NumbersList
for(int i = 0; i < MAX_ELEMENTS; i++)
NumbersList.push_back(i) ;
first = NumbersList.begin() ; // location of first
// element of NumbersList
last = NumbersList.end() ; // one past the location
// last element of NumbersList
// print content of NumbersList
cout << "NumbersList { " ;
for(itl = first; itl != last; itl++)
cout << *itl << " " ;
cout << " }\n" << endl ;
// merge the elements of NumbersVector
// and NumbersList and place the
// results in NumbersDeque
merge(startv, endv, first, last, NumbersDeque.begin()) ;
cout << "After calling merge\n" << endl ;
// print content of NumbersDeque
cout << "NumbersDeque { " ;
for(itd = NumbersDeque.begin();
itd != NumbersDeque.end(); itd++)
cout << *itd << " " ;
cout << " }\n" << endl ;
}
Program Output
NumbersVector { 4 10 10 30 69 70 96 100 }
NumbersList { 0 1 2 3 4 5 6 7 }
After calling merge
NumbersDeque { 0 1 2 3 4 4 5 6 7 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 <vector>
#include <list>
#include <deque>
using namespace std ;
void main()
{
const int MAX_ELEMENTS = 8 ;
// Define a template class vector of int
typedef vector<int> IntVector ;
//Define an iterator for template class vector of ints
typedef IntVector::iterator IntVectorIt ;
IntVector NumbersVector(MAX_ELEMENTS) ;
IntVectorIt startv, endv, itv ;
// Define a template class list of int
typedef list<int> IntList ;
//Define an iterator for template class list of ints
typedef IntList::iterator IntListIt ;
IntList NumbersList ;
IntListIt first, last, itl ;
// Define a template class deque of int
typedef deque<int> IntDeque ;
//Define an iterator for template class deque of ints
typedef IntDeque::iterator IntDequeIt ;
IntDeque NumbersDeque(2 * MAX_ELEMENTS) ;
IntDequeIt itd ;
// Initialize vector NumbersVector
NumbersVector[0] = 4 ;
NumbersVector[1] = 10;
NumbersVector[2] = 70 ;
NumbersVector[3] = 10 ;
NumbersVector[4] = 30 ;
NumbersVector[5] = 69 ;
NumbersVector[6] = 96 ;
NumbersVector[7] = 100;
startv = NumbersVector.begin() ; // location of first
// element of NumbersVector
endv = NumbersVector.end() ; // one past the location
// last element of NumbersVector
// sort NumbersVector, merge requires the sequences
// to be sorted
sort(startv, endv, less<int>()) ;
// print content of NumbersVector
cout << "NumbersVector { " ;
for(itv = startv; itv != endv; itv++)
cout << *itv << " " ;
cout << " }\n" << endl ;
// Initialize vector NumbersList
for(int i = 0; i < MAX_ELEMENTS; i++)
NumbersList.push_back(i) ;
first = NumbersList.begin() ; // location of first
// element of NumbersList
last = NumbersList.end() ; // one past the location
// last element of NumbersList
// print content of NumbersList
cout << "NumbersList { " ;
for(itl = first; itl != last; itl++)
cout << *itl << " " ;
cout << " }\n" << endl ;
// merge the elements of NumbersVector
// and NumbersList and place the
// results in NumbersDeque
merge(startv, endv, first, last, NumbersDeque.begin(), less<int>()) ;
cout << "After calling merge\n" << endl ;
// print content of NumbersDeque
cout << "NumbersDeque { " ;
for(itd = NumbersDeque.begin();
itd != NumbersDeque.end(); itd++)
cout << *itd << " " ;
cout << " }\n" << endl ;
}
Program Output
NumbersVector { 4 10 10 30 69 70 96 100 }
NumbersList { 0 1 2 3 4 5 6 7 }
After calling merge
NumbersDeque { 0 1 2 3 4 4 5 6 7 10 10 30 69 70 96 100 }
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
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.
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.
Merge sorted ranges. Combines the elements in the sorted ranges [first1,last1) and [first2,last2), into a new range beginning at result with all its elements sorted. The C++ algorithm::merge function is used to merge elements of sorted ranges [first1, last1) and [first2, last2) to the range starting at result. In default version elements are compared using operator< and in custom version elements are compared using comp. The elements are compared using operator< for the first version, and comp for the second. The elements in both ranges shall already be ordered according to this same criterion (operator< or comp). The resulting range is also sorted according to this.
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.
Return iterator to beginning. Returns an iterator pointing to the first element in the deque container. Notice that, unlike member deque::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. deque::begin() is an inbuilt function in C++ STL which is declared in header file. deque::begin() returns an iterator which is referencing to the first element of the deque container associated with the function. Both begin() and end() are used to iterate through the deque container. 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.
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.
Return iterator to end. Returns an iterator referring to the past-the-end element in the deque container. The past-the-end element is the theoretical element that would follow the last element in the deque container. 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 deque::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as deque::begin. deque::end() is an inbuilt function in C++ STL which is declared in<deque> header file. deque::end() returns an iterator which is referencing next to the last element of the deque container associated with the function. Both begin() and end() are used to iterate through the deque container.
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.
List is a popularly used sequence container. Container is an object that holds data of same type. List container is implemented as doubly linked-list, hence it provides bidirectional sequential access to it's data. List doesn't provide fast random access, it only supports sequential access in both directions. List allows insertion and deletion operation anywhere within a sequence in constant time. Elements of list can be scattered in different chunks of memory. Container stores necessary information to allow sequential access to it's data. Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by internal allocator. Zero sized lists are also valid. In that case list.begin() and list.end() points to same location. But behavior of calling front() or back() is undefined. To define the std::list, we have to import the <list> header file.
Sort elements in range. Sorts the elements in the range [first,last) into ascending order. The elements are compared using operator< for the first version, and comp for the second. Equivalent elements are not guaranteed to keep their original relative order (see stable_sort). C++ Algorithm sort() function is used to sort the elements in the range [first, last) into ascending order. The elements are compared using operator < for the first version, and comp for the second version. std::sort() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and (by default) sorts the iterable in ascending order. The function can also be used for custom sorting by passing in a comparator function that returns a boolean.
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.
deque (usually pronounced like "deck") is an irregular acronym of double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be expanded or contracted on both ends (either its front or its back). Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any case, they allow for the individual elements to be accessed directly through random access iterators, with storage handled automatically by expanding and contracting the container as needed. Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of elements also at the beginning of the sequence, and not only at its end. But, unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations: accessing elements in a deque by offsetting a pointer to another element causes undefined behavior.
Add element at the end. Adds a new element at the end of the list container, after its current last element. The content of val is copied (or moved) to the new element. This effectively increases the container size by one. The list:push_back() function in C++ STL is used to add a new element to an existing list container. It takes the element to be added as a parameter and adds it to the list container. This function accepts a single parameter which is mandatory value. This refers to the element needed to be added to the list, list_name. This function does not return any value.
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.
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 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, 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.
Return iterator to end. Returns an iterator referring to the past-the-end element in the list container. The past-the-end element is the theoretical element that would follow the last element in the list container. 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 list::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as list::begin. This function does not accept any parameter.
Return iterator to beginning. Returns an iterator pointing to the first element in the list container. Notice that, unlike member list::front, which returns a reference to the first element, this function returns a bidirectional iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container. This function does not accept any parameter. Function returns an iterator to the beginning of the sequence container.
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.
To concatenate strings in 'C++' Programming, you have to ask to enter the 2 string and start concatenating one string into other using the strcat() function as shown here in the sample
Similar to friend class, this 'C++ Function' can access the private and protected members of another class. A 'Global Function' can also be 'declared as friend' as shown in the C++ Code
The digit sum of a given integer is the sum of all its digits (digit sum of '84001' is calculated as 8+4+0+0+1 = 13). Odd number is an integer which is not a multiple of two. If it is "divided"