C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
Algorithm copy - Copies elements from one range to another.
Algorithm copy - Copies elements from one range to another.
copy
Header
<algorithm>
template<class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first1, InputIterator last1, OutputIterator first2) ;
Copies elements from one range to another. copy copies elements from the range [first1, last1) into a range of the same size starting at first2. It uses the assignment operator to replace existing elements. copy returns an iterator positioned immediately after the new last element.
The algorithm proceeds in the forward direction copying source elements first1, first+1, ..., last1 - 1. The destination range can overlap with the source range provided it doesn't contain first2.
Sample
#pragma warning (disable: 4786)
#include <algorithm>
#include <vector>
#include <deque>
#include <iostream>
int main()
{
std::vector<int> vint ;
std::deque<int> dint(25) ;
typedef std::ostream_iterator <int> IntOstreamIt;
std::deque<int>::iterator dit ;
int i ;
for(i = 0 ; i < 25; i++)
vint.push_back(i*i) ;
std::cout << "copy contents of vector to deque using copy\n" << std::endl ;
//copy contents of vector to deque.
dit = std::copy(vint.begin(), vint.end(), dint.begin()) ;
std::cout << "last element of dint = " << *(dit - 1) << "\n" << std::endl ;
IntOstreamIt OstreamIt(std::cout,", ");
std::cout << "vint = " ;
std::copy(vint.begin(), vint.end(), OstreamIt);
std::cout << "\n" << std::endl ;
std::cout << "dint = " ;
std::copy(dint.begin(), dint.end(), OstreamIt);
std::cout << std::endl ;
std::cout << "copy contents of vector to deque using copy_backward\n" << std::endl ;
//copy contents of vector to deque,
//copy_backward starts copying elements from the end of the vector
//and progresses to the start of the vector.
//It returns pointer to the last element in the deque
dit = std::copy_backward(vint.begin(), vint.end(), dint.begin()) ;
std::cout << "first element of dint = " << *dit << "\n" << std::endl ;
std::cout << "vint = " ;
std::copy(vint.begin(), vint.end(), OstreamIt);
std::cout << "\n" << std::endl ;
std::cout << "dint = " ;
std::copy(dint.begin(), dint.end(), OstreamIt);
std::cout << std::endl ;
return 0 ;
}
Program Output
copy contents of vector to deque using copy
last element of dint = 576
vint = 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 28
9, 324, 361, 400, 441, 484, 529, 576,
dint = 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 28
9, 324, 361, 400, 441, 484, 529, 576,
copy contents of vector to deque using copy_backward
first element of dint = 0
vint = 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 28
9, 324, 361, 400, 441, 484, 529, 576,
dint = 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 28
9, 324, 361, 400, 441, 484, 529, 576,
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.
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.
copy() function is used to copy items from one iterator to another iterator with a specific range. We can define the start and end position of the source and it will copy all items in this rage to a different destination. To use copy() function, we need to include <bits/stdc+.h> or header file. It copies all the elements pointed by first and last. first element is included in the output but last is not. output is the start position of the final result iterator. It returns one iterator to the end of the destination range where elements have been copied. Function returns an iterator to the end of the destination range where elements have been copied.
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 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.
#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.
Ostream iterators are output iterators that write sequentially to an output stream (such as cout). They are constructed from a basic_ostream object, to which they become associated, so that whenever an assignment operator (=) is used on the ostream_iterator (dereferenced or not) it inserts a new element into the stream. Optionally, a delimiter can be specified on construction. This delimiter is written to the stream after each element is inserted.
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.
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.
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.
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.
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.
Add element at the end. Adds a new element at the end of the vector, 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, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity. push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1. This function does not return any value.
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.
Copy range of elements backward. Copies the elements in the range [first,last) starting from the end into the range terminating at result. The C++ function std::algorithm::copy_backward() copies a range of elements to a new location in backward order. The function returns an iterator to the first element in the destination range. The resulting range has the elements in the exact same order as [first,last). To reverse their order, see reverse_copy. The function begins by copying *(last-1) into *(result-1), and then follows backward by the elements preceding these, until first is reached (and including it). The ranges shall not overlap in such a way that result (which is the past-the-end element in the destination range) points to an element in the range (first,last].
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 this example, 'frequency of characters' in a String object is computed. To do this, "size()" function is used to find the Length of a string object. Then, the for loop is iterated until the
C++ language allows us to separate program-specific datatypes through the use of classes. "C++ Classes" define types of data structures and the functions that operate on those data