C++ Programming Code Examples
C++ > Code Snippets Code Examples
Check for mismatch between two vectors
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
/* Check for mismatch between two vectors */
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
int a1[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int a2[ 10 ] = { 1, 2, 3, 4, 9, 6, 7, 8, 9, 10 };
std::vector< int > v1( a1, a1 + 10 );
std::vector< int > v2( a1, a1 + 10 );
std::vector< int > v3( a2, a2 + 10 );
std::ostream_iterator< int > output( cout, " " );
cout << "Vector v1 contains: ";
std::copy( v1.begin(), v1.end(), output );
cout << "\nVector v2 contains: ";
std::copy( v2.begin(), v2.end(), output );
cout << "\nVector v3 contains: ";
std::copy( v3.begin(), v3.end(), output );
std::pair< std::vector< int >::iterator, std::vector< int >::iterator > loca
tion;
location = std::mismatch( v1.begin(), v1.end(), v3.begin() );
cout << "\nThere is a mismatch between v1 and v3 at location "
<< ( location.first - v1.begin() ) << "\nwhere v1 contains "
<< *location.first << " and v3 contains " << *location.second;
return 0;
}
/*
Vector v1 contains: 1 2 3 4 5 6 7 8 9 10
Vector v2 contains: 1 2 3 4 5 6 7 8 9 10
Vector v3 contains: 1 2 3 4 9 6 7 8 9 10
There is a mismatch between v1 and v3 at location 4
where v1 contains 5 and v3 contains 9
*/
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;
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;
}
Vectors in C++ Language
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.
Declaration for Vectors in C++
std::vector<T> vector_name;
Initialization for Vectors in C++
// Vector initialization method 1
// Initializer list
vector<int> vector1 = {1, 2, 3, 4, 5};
// Vector initialization method 2
vector<int> vector3(5, 12);
vector<int> vector2 = {8, 8, 8, 8, 8};
Syntax for Vector Iterators in C++
vector<T>::iterator iteratorName;
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
/* Vectors in C++ language */
// C++ program to illustrate the capacity function in vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> myvector;
for (int i = 1; i <= 5; i++)
myvector.push_back(i);
cout << "Size : " << myvector.size();
cout << "\nCapacity : " << myvector.capacity();
cout << "\nMax_Size : " << myvector.max_size();
// resizes the vector size to 4
myvector.resize(4);
// prints the vector size after resize()
cout << "\nSize : " << myvector.size();
// checks if the vector is empty or not
if (myvector.empty() == false)
cout << "\nVector is not empty";
else
cout << "\nVector is empty";
// Shrinks the vector
myvector.shrink_to_fit();
cout << "\nVector elements are: ";
for (auto it = myvector.begin(); it != myvector.end(); it++)
cout << *it << " ";
return 0;
}
Vector Library begin() Function in C++
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.
Syntax for Vector begin() Function in C++
#include <vector>
iterator begin() noexcept;
const_iterator begin() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements 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
22
/* returns a random access iterator pointing to the first element of the vector by std::vector::begin() function code example. */
// CPP program to illustrate implementation of begin() function
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// declaration of vector container
vector<string> myvector{ "This", "is",
"HappyCodings" };
// using begin() to print vector
for (auto it = myvector.begin();
it != myvector.end(); ++it)
cout << ' ' << *it;
return 0;
}
Algorithm Library mismatch() Function in C++
Return first position where two ranges differ. Compares the elements in the range [first1,last1) with those in the range beginning at first2, and returns the first element of both sequences that does not match. C++ Algorithm mismatch() function compares both the containers to spot for any mismatch of values. The function returns the first element of both the containers that does not match. The elements are compared using operator== (or pred, in version (2)).
Syntax for Algorithm mismatch() Function in C++
#include <algorithm>
//equality (1)
template <class InputIterator1, class InputIterator2>
pair<InputIterator1, InputIterator2>
mismatch (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2);
//predicate (2)
template <class InputIterator1, class InputIterator2, class BinaryPredicate>
pair<InputIterator1, InputIterator2>
mismatch (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, BinaryPredicate pred);
first1, last1
Input iterators to the initial and final positions of the first sequence. The range used is [first1,last1), which contains all the elements between first1 and last1, including the element pointed by first1 but not the element pointed by last1.
first2
Input iterator to the initial position of the second sequence. Up to as many elements as in the range [first1,last1) can be accessed by the function.
pred
Binary function that accepts two elements as argument (one of each of the two sequences, in the same order), and returns a value convertible to bool. The value returned indicates whether the elements are considered to match in the context of this function.
The function shall not modify any of its arguments. This can either be a function pointer or a function object.
Function returns a pair, where its members first and second point to the first element in both sequences that did not compare equal to each other.
If the elements compared in both sequences have all matched, the function returns a pair with first set to last1 and second set to the element in that same relative position in the second sequence.
If none matched, it returns make_pair(first1,first2).
If the function finds a pair of elements that does not match then it returns the first pair of such element, one from each container.
In case none of the elements from the containers match the the function returns the pair(first1, first2)
If the entire element in the pair matches then the function returns a pair of last1 and the element with same respective position to last1 in the second container.
Complexity
Up to linear in the distance between first1 and last1: Compares elements until a mismatch is found.
Data races
Some (or all) of the objects in both ranges are accessed (once at most).
Exceptions
Throws if any element comparison (or pred) throws or if any of the operations on iterators throws. Note that invalid parameters 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
/* find mismatches in elements of two containers by mismatch() function code example */
/* return first position where two ranges differ */
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> vector1= {10, 20, 30, 40};
vector<int> vector2= {10, 20, 33, 40};
vector<int> vector3= {10, 20, 30};
vector<int> vector4= {10, 20, 30, 40, 50};
pair< vector<int>::iterator, vector<int>::iterator > mismatch_pair;
mismatch_pair = mismatch(vector1.begin(), vector1.end(), vector2.begin());
cout << "The first mismatch pair from vector1 and vector2 is: ";
cout << *mismatch_pair.first << " " << *mismatch_pair.second << endl;
mismatch_pair = mismatch(vector3.begin(), vector3.end(), vector4.begin());
cout << "The first mismatch pair from vector3 and vector4 is: ";
cout << *mismatch_pair.first << " " << *mismatch_pair.second;
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;
}
Vector Library end() Function in C++
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.
Syntax for Vector end() Function in C++
#include <vector>
iterator end() noexcept;
const_iterator end() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements 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
22
/* returns the iterator pointing to the past-the-last element of the vector container by vector::end function code example. */
// CPP program to illustrate implementation of begin() function
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// declaration of vector container
vector<string> myvector{ "This", "is",
"HappyCodings" };
// using begin() to print vector
for (auto it = myvector.begin();
it != myvector.end(); ++it)
cout << ' ' << *it;
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;
}
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;
}
Pairs in C++ Language
In C++, pair is defined as a container in a header library <utility> which combines the two data elements having either the same data types or different data types. In general, the pair in C++ is defined as a tuple in Python programming language which also can give the output as a combined result of joining the two items specified by the pair container and it consists of the first element will be first and the second element will be second only it cannot be disturbed in the order or sequence of elements specified and are always accessed by the dot operator followed by the keyword "first" and "second" elements respectively.
In C++ the pair is a container in <utility> header and is also a container class in STL (Standard Template Library) which uses "std" namespace so it will be as std::pair template class for demonstrating pair as a tuple.
Declaring a Pair in C++
#include <utility>
pair(dt1, dt2) pairname;
dt1
datatype for the first element.
dt2
datatype for the second element.
pairname
a name which is used to refer to the pair objects .first and .second elements.
Initializing a Pair
pair (data_type1, data_type2) Pair_name (value1, value2) ;
pair g1; //default
pair g2(1, 'a'); //initialized, different data type
pair g3(1, 10); //initialized, same data type
pair g4(g3); //copy of g3
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
/* working of pair in C++ language code examples */
#include <iostream>
#include<utility>
using namespace std;
int main()
{
pair<int, int>pair1 = make_pair(90, 100);
pair<int, int>pair2 = make_pair(4, 30);
cout<< "Use of operators with pair and it results in true (1) or false (0)";
cout << (pair1 <= pair2) << endl;
cout << (pair1 >= pair2) << endl;
cout << (pair1 > pair2) << endl;
cout << (pair1 < pair2) << endl;
cout << (pair1 == pair2) << endl;
cout << (pair1 != pair2) << endl;
cout << "Use of swap function with pair";
cout << "Before swapping:\n" ;
cout << "Contents of pair1 = " << pair1.first << " " << pair1.second << "\n";
cout << "Contents of pair2 = " << pair2.first << " " << pair2.second << "\n";
pair1.swap(pair2);
cout << "\nAfter swapping:\n";
cout << "Contents of pair1 = " << pair1.first << " " << pair1.second << "\n " ;
cout << "Contents of pair2 = " << pair2.first << " " << pair2.second << "\n" ;
return 0;
}
#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"
#include <header_file>
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;
}
To swap two numbers in C++, ask to the user to enter the two number, and store both the number in the variable say num1 and num2. Now to swap both the number, first, make a
This C++ Program perform 'encoding matrix' using a hidden-key. "Encoding" is performed using "matrix multiplication" between given matrix and 'key matrix'. Enter the number of