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

Use std::copy to print all elements in a set

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* Use std::copy to print all elements in a set */ #include <iostream> using std::cout; using std::endl; #include <set> #include <algorithm> #include <iterator> // ostream_iterator int main() { double a[ 5 ] = { 2.1, 4.2, 9.5, 2.1, 3.7 }; std::set< double, std::less< double > > doubleSet( a, a + 5 );; std::ostream_iterator< double > output( cout, " " ); cout << "doubleSet contains: "; std::copy( doubleSet.begin(), doubleSet.end(), output ); cout << endl; return 0; } /* doubleSet contains: 2.1 3.7 4.2 9.5 */
#include Directive in C++
#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.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
Set Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the set container. end() function returns an iterator pointing to past the last element of the set container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator. The past-the-end element is the theoretical element that would follow the last element in the set 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 set::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as set::begin.
Syntax for Set end() Function in C++
#include <set> iterator end() noexcept; const_iterator end() const noexcept;
This function does not accept any parameter. Function returns an iterator to the past-the-end element in the container. If the set object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are bidirectional iterator types pointing to elements.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Set::end() function is a bidirectional iterator used to return an iterator pointing to the last element of the set container. */ // CPP program code example to illustrate implementation of end() function #include <iostream> #include <set> using namespace std; int main() { // declaration of set container set<char> myset{ 'a', 'c', 'g', 'z' }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0; }
Functional Library less in C++
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.
Syntax for Functional less in C++
#include <functional> template <class T> struct less;
T
Type of the arguments to compare by the functional call. The type shall support the operation (operator<). This function does not return any value. Objects of this class can be used on standard algorithms such as sort, merge or lower_bound.
Member types & definition
• first_argument_type T Type of the first argument in member operator() • second_argument_type T Type of the second argument in member operator() • result_type bool Type returned by member operator()
Member functions
bool operator() (const T& x, const T& y) Member function returning whether the first argument compares less than the second (x<y).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/* The std::less is a is a member of the functional class (<functional.h>) used for performing comparisons. It is defined as a function object class for less than inequality comparison which returns a boolean value depending upon the condition. This can be used to change the functionality of the given function. It can be used with various standard algorithms like sort, lower_bound etc. */ /* Function object class for less-than inequality comparison by std::less function code example */ #include <algorithm> #include <functional> #include <iostream> using namespace std; // Function to print array arr[] void printArray(int arr[], int N) { for (int i = 0; i < N; i++) { cout << arr[i] << ' '; } } // Driver Code int main() { int arr[] = { 26, 23, 21, 22, 28, 27, 25, 24 }; int N = sizeof(arr) / sizeof(arr[0]); // Sort the array in increasing order sort(arr, arr + N, less<int>()); // Print sorted array printArray(arr, N); return 0; }
main() Function in C++
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.
Syntax for main() Function in C++
void main() { ............ ............ }
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }
Sets in C++ Language
Sets are part of the C++ STL (Standard Template Library). Sets are the associative containers that stores sorted key, in which each key is unique and it can be inserted or deleted but cannot be altered. Sets are containers that store unique elements following a specific order. In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container. Internally, the elements in a set are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare). set containers are generally slower than unordered_set containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order. Sets are typically implemented as binary search trees.
Syntax for Sets in C++
template < class T, // set::key_type/value_type class Compare = less<T>, // set::key_compare/value_compare class Alloc = allocator<T> // set::allocator_type > class set;
T
Type of the elements. Each element in a set container is also uniquely identified by this value (each value is itself also the element's key). Aliased as member types set::key_type and set::value_type.
Compare
A binary predicate that takes two arguments of the same type as the elements and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are key values, shall return true if a is considered to go before b in the strict weak ordering the function defines. The set object uses this expression to determine both the order the elements follow in the container and whether two element keys are equivalent (by comparing them reflexively: they are equivalent if !comp(a,b) && !comp(b,a)). No two elements in a set container can be equivalent. This can be a function pointer or a function object (see constructor for an example). This defaults to less<T>, which returns the same as applying the less-than operator (a<b). Aliased as member types set::key_compare and set::value_compare.
Alloc
Type of the allocator object used to define the storage allocation model. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent. Aliased as member type set::allocator_type. Container properties: • Associative - Elements in associative containers are referenced by their key and not by their absolute position in the container. • Ordered - The elements in the container follow a strict order at all times. All inserted elements are given a position in this order. • Set - The value of an element is also the key used to identify it. • Unique keys - No two elements in the container can have equivalent keys. • Allocator-aware - The container uses an allocator object to dynamically handle its storage needs. Member Functions for Sets Below is the list of all member functions of Set: • (constructor): Construct set. • (destructor): Set destructor. • operator=: Copy elements of the set to another set. • begin: Returns an iterator pointing to the first element in the set. • cbegin: Returns a const iterator pointing to the first element in the set. • end: Returns an iterator pointing to the past-end. • cend: Returns a constant iterator pointing to the past-end. • rbegin: Returns a reverse iterator pointing to the end. • rend: Returns a reverse iterator pointing to the beginning. • crbegin: Returns a constant reverse iterator pointing to the end. • crend: Returns a constant reverse iterator pointing to the beginning. • empty: Returns true if set is empty. • size: Returns the number of elements in the set. • max_size: Returns the maximum size of the set. • insert: Insert element in the set. • erase: Erase elements from the set. • swap: Exchange the content of the set. • clear: Delete all the elements of the set. • emplace: Construct and insert the new elements into the set. • emplace_hint: Construct and insert new elements into the set by hint. • key_comp: Return a copy of key comparison object. • value_comp: Return a copy of value comparison object. • find: Search for an element with given key. • count: Gets the number of elements matching with given key. • lower_bound: Returns an iterator to lower bound. • upper_bound: Returns an iterator to upper bound. • equal_range: Returns the range of elements matches with given key. • get_allocator: Returns an allocator object that is used to construct the set. • operator==: Checks whether the two sets are equal or not. • operator!=: Checks whether the two sets are equal or not. • operator<: Checks whether the first set is less than other or not. • operator<=: Checks whether the first set is less than or equal to other or not. • operator>: Checks whether the first set is greater than other or not. • operator>=: Checks whether the first set is greater than equal to other or not. • swap(): Exchanges the element of two sets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* A set is an Associative container which contains a sorted set of unique objects of type Key. Each element may occur only once, so duplicates are not allowed. */ #include<bits/stdc++.h> using namespace std; int main() { set < int > s; // inserting elements in random order . s.insert( 60 ) ; s.insert( 10 ) ; s.insert( 20 ) ; s.insert( 20 ) ; s.insert( 40 ) ; s.insert( 50 ) ; // printing set s //initialising the iterator, iterating to the beginning of the set. set<int >::iterator it ; cout << "The element of set s are : \n"; for (it = s.begin() ; it != s.end() ; it++ ) { cout << *it<<" "; } cout << endl; cout<< "The size of set : \n " << s.size() <<endl ; return 0 ; }
Set Library begin() Function in C++
Return iterator to beginning. Returns an iterator referring to the first element in the set container. Because set containers keep their elements ordered at all times, begin points to the element that goes first following the container's sorting criterion. The C++ set::begin function returns the iterator pointing to the first element of the set. Please note that, Set is an ordered data container which implies all its elements are ordered all the time. If the container is empty, the returned iterator value shall not be dereferenced.
Syntax for Set begin() Function in C++
#include <set> iterator begin() noexcept; const_iterator begin() const noexcept;
This function does not accept any parameter. Function returns an iterator to the first element in the container. If the set object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are bidirectional iterator types pointing to elements.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). Concurrently accessing the elements of a set is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Set::begin() function is a bidirectional iterator used to return an iterator pointing to the first element of the set container. */ // CPP program code example to illustrate implementation of begin() function #include <iostream> #include <set> using namespace std; int main() { // declaration of set container set<int> myset{ 1, 2, 3, 4, 5 }; // using end() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0; }
Algorithm Library copy() Function in C++
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.
Syntax for copy() Function in C++
template <class InputIterator, class OutputIterator> OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
first
It is an input iterator to the first element of the range, where the element itself is included in the range.
last
It is an input iterator to the last element of the range, where the element itself is not included in the range. Input iterators to the initial and final positions in a sequence to be copied. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
result
It is an output iterator to the first element of the new container in which the elements are copied. Output iterator to the initial position in the destination sequence. This shall not point to any element in the range [first,last). Function returns an iterator to the end of the destination range where elements have been copied.
Complexity
Linear in the distance between first and last: Performs an assignment operation for each element in the range.
Data races
The objects in the range [first,last) are accessed (each object is accessed exactly once). The objects in the range between result and the returned value are modified (each object is modified exactly once).
Exceptions
Throws if either an element assignment or an operation on iterators throws. Note that invalid arguments cause undefined behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* copying the array elements to the vector by copy() function code example */ // C++ STL program to demonstrate use of std::copy() function #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { //declaring & initializing an int array int arr[] = { 10, 20, 30, 40, 50 }; //vector declaration vector<int> v1(5); //copying array elements to the vector copy(arr, arr + 5, v1.begin()); //printing array cout << "arr: "; for (int x : arr) cout << x << " "; cout << endl; //printing vector cout << "v1: "; for (int x : v1) cout << x << " "; cout << endl; return 0; }
Ostream Library put() Function in C++
Put character. Inserts character c into the stream. Internally, the function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts c into its associated stream buffer object as if calling its member function sputc, and finally destroys the sentry object before returning.
Syntax for Ostream put() Function in C++
ostream& put (char c);
c
Character to write Function returns the ostream object (*this). Errors are signaled by modifying the internal state flags: • eofbit - • failbit May be set if the construction of sentry failed. • badbit Either the insertion on the stream failed, or some other error happened (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected. Multiple flags may be set by a single operation. If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure. Through the previous study, we know that C++ programs generally use the cout output stream object of the ostream class and the << output operator to achieve output, and the cout output stream has a corresponding buffer in memory. But sometimes users have special output requirements, such as outputting only one character. In this case, you can use the put() member method provided by this class to achieve.
Data races
Modifies the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream objects (cout, cerr, clog) when these are synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which characters from multiple threads are inserted).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state. Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/* It is used to inserts character c into the stream.this function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts c into its associated stream buffer object as if calling its member function sputc, and finally destroys the sentry object before returning. */ //C++ code example to Writing data to a file using put() function and ios::out mode #include<iostream> #include<fstream> #include<cstring> using namespace std; int main() { //Creating an output stream to write data to a file ofstream ofstream_ob; //Opens/creates a file named File2.txt ofstream_ob.open("File2.txt", ios::out); char arr[100] = "Hello World. We wish you best in everything. Never give up!"; int length = strlen(arr); char ch; //Reading the char array i.e. a character at a time and writing it to the file for(int i=0; i<length; i++) { ch = arr[i]; ofstream_ob.put(ch); //Writing a character to file, by using put() function } //Closing the output stream ofstream_ob.close(); return 0; }
Iterators in C++ Language
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.
Syntax for Iterators in C++
<ContainerType> :: iterator; <ContainerType> :: const_iterator;
• 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. • Iterators provide a generic approach to navigate through the elements of a container. Operator (*) : The '*' operator returns the element of the current position pointed by the iterator. Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator points to the next element of the container. Operator (==) and Operator (!=) : Both these operators determine whether the two iterators point to the same position or not. Operator (=) : The '=' operator assigns the iterator. Iterators can be smart pointers which allow to iterate over the complex data structures. A Container provides its iterator type. Therefore, we can say that the iterators have the common interface with different container type. The container classes provide two basic member functions that allow to iterate or move through the elements of a container: begin(): The begin() function returns an iterator pointing to the first element of the container. end(): The end() function returns an iterator pointing to the past-the-last element of the container. Input Iterator: An input iterator is an iterator used to access the elements from the container, but it does not modify the value of a container. Operators used for an input iterator are: Increment operator(++), Equal operator(==), Not equal operator(!=), Dereference operator(*). Output Iterator: An output iterator is an iterator used to modify the value of a container, but it does not read the value from a container. Therefore, we can say that an output iterator is a write-only iterator. Operators used for an output iterator are: Increment operator(++), Assignment operator(=). Forward Iterator: A forward iterator is an iterator used to read and write to a container. It is a multi-pass iterator. Operators used for a Forward iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=). Bidirectional iterator: A bidirectional iterator is an iterator supports all the features of a forward iterator plus it adds one more feature, i.e., decrement operator(--). We can move backward by decrementing an iterator. Operators used for a Bidirectional iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=), Decrement operator(--). Random Access Iterator: A Random Access iterator is an iterator provides random access of an element at an arbitrary location. It has all the features of a bidirectional iterator plus it adds one more feature, i.e., pointer addition and pointer subtraction to provide random access to an element. Following are the disadvantages of an iterator: • If we want to move from one data structure to another at the same time, iterators won't work. • If we want to update the structure which is being iterated, an iterator won?t allow us to do because of the way it stores the position. • If we want to backtrack while processing through a list, the iterator will not work in this case. Following are the advantages of an iterator: • Ease in programming: It is convenient to use iterators rather than using a subscript operator[] to access the elements of a container. If we use subscript operator[] to access the elements, then we need to keep the track of the number of elements added at the runtime, but this would not happen in the case of an iterator. • Code Reusability: A code can be reused if we use iterators. In the above example, if we replace vector with the list, and then the subscript operator[] would not work to access the elements as the list does not support the random access. However, we use iterators to access the elements, then we can also access the list elements. • Dynamic Processing: C++ iterators provide the facility to add or delete the data dynamically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/* Iterators in C++ language */ // C++ code to demonstrate the working of next() and prev() #include<iostream> #include<iterator> // for iterators #include<vector> // for vectors using namespace std; int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterators to a vector vector<int>::iterator ptr = ar.begin(); vector<int>::iterator ftr = ar.end(); // Using next() to return new iterator // points to 4 auto it = next(ptr, 3); // Using prev() to return new iterator // points to 3 auto it1 = prev(ftr, 3); // Displaying iterator position cout << "The position of new iterator using next() is : "; cout << *it << " "; cout << endl; // Displaying iterator position cout << "The position of new iterator using prev() is : "; cout << *it1 << " "; cout << endl; return 0; }
Iterator Library ostream_iterator in C++
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.
Syntax for Iterator ostream_iterator in C++
#include <iterator> template <class T, class charT=char, class traits=char_traits<charT> > class ostream_iterator;
T
Element type for the iterator: The type of elements inserted into the stream
charT
First template parameter of the associated basic_ostream object: The type of elements the stream handles (char for ostream).
traits
Second template parameter of the associated basic_ostream: Character traits for the elements the stream handles. The default template arguments correspond to an instantiation that uses an ostream object as associated stream.
Member types
Member types & definition in istream_iterator ostream_type: basic_ostream<charT,traits> --- Type of the associated output stream iterator_category: output_iterator_tag --- Input iterator value_type: void char_type: charT --- Type of the characters handled by the associated stream traits_type: traits --- Character traits for associated stream difference_type: void pointer: void reference: void
Member functions
• (constructor) Construct ostream iterator (public member function ) • operator* Dereference iterator (public member function ) • operator++ Increment iterator (public member function ) • operator= Assignment operator (public member function )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/* C++ ostream_iterator is a special output iterator that write sequentially to an output stream. */ /* ostream_iterator class template - Output iterator to write items to an ostream */ /* C++ code example to illustrate read a bunch of strings from a file sort them lexicographically and print them to output stream */ #include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <vector> using namespace std; int main() { // Define a vector to store the strings received from input vector<string> strings_v; // Define the filestream object used to read data from file ifstream fin("input_file.txt"); // Get input stream and end of stream iterators istream_iterator<string> fin_it(fin); istream_iterator<string> eos; // Get output stream iterators ostream_iterator<string> cout_it(cout, " "); // Copy elements from input to vector using copy function copy(fin_it, eos, back_inserter(strings_v)); // Sort the vector sort(strings_v.begin(), strings_v.end()); // Copy elements from vector to output copy(strings_v.begin(), strings_v.end(), cout_it); return 0; }


C++ program, "using iteration", implements the list of elements removed from the stack in last in first out mode using a linked list. A linked list is an ordered set of data elements,
You have to ask to the user to enter array size array elements to store all the array elements in one dimensional and then print the array in "one dimension" using one for loop as shown