C++ Programming Code Examples
C++ > Code Snippets Code Examples
Use std::unique to eliminate duplicate values
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
/* Use std::unique to eliminate duplicate values */
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
int a1[ 5 ] = { 1, 1, 1, 7, 9 };
std::vector< int > v1( a1, a1 + 5 );
std::ostream_iterator< int > output( cout, " " );
std::copy( v1.begin(), v1.end(), output ); // display vector output
// eliminate duplicate values
std::vector< int >::iterator endLocation;
endLocation = std::unique( v1.begin(), v1.end() );
cout << endl;
std::copy( v1.begin(), endLocation, output );
return 0;
}
/*
1 1 1 7 9
1 7 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;
}
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;
}
#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;
}
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;
}
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;
}
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 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;
}
Algorithm Library unique() Function in C++
Remove consecutive duplicates in range. Removes all but the first element from every consecutive group of equivalent elements in the range [first,last). std::unique is used to remove duplicates of any element present consecutively in a range[first, last). It performs this task for all the sub-groups present in the range having the same element present consecutively.
The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to the element that should be considered its new past-the-end element.
The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state.
The function uses operator== to compare the pairs of elements (or pred, in version (2)).
Syntax for Algorithm unique() Function in C++
#include <algorithm>
//equality (1)
template <class ForwardIterator>
ForwardIterator unique (ForwardIterator first, ForwardIterator last);
//predicate (2)
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique (ForwardIterator first, ForwardIterator last,
BinaryPredicate pred);
first, last
Forward iterators to the initial and final positions of the sequence of move-assignable elements. 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.
pred
Binary function that accepts two elements in the range as argument, and returns a value convertible to bool. The value returned indicates whether both arguments are considered equivalent (if true, they are equivalent and one of them is removed).
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
Function returns an iterator to the element that follows the last element not removed.
The range between first and this iterator includes all the elements in the sequence that were not considered duplicates.
Complexity
For non-empty ranges, linear in one less than the distance between first and last: Compares each pair of consecutive elements, and possibly performs assignments on some of them.
Data races
The objects in the range [first,last) are accessed and potentially modified.
Exceptions
Throws if any of pred, the element comparisons, the element assignments or the operations 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
/* C++ Algorithm unique() function is used to transform a sequence in such a way that each duplicate consecutive element becomes a unique element. */
/* remove duplicates of any element present consecutively in a range[first, last) by std::unique function code example. */
// C++ program code example to demonstrate the use of std::unique
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v = { 1, 1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8 }, i;
vector<int>::iterator ip;
// Using std::unique
ip = std::unique(v.begin(), v.begin() + 12);
// Now v becomes {1 3 10 1 3 7 8 * * * * *}
// * means undefined
// Resizing the vector so as to remove the undefined terms
v.resize(std::distance(v.begin(), ip));
// Displaying the vector after applying std::unique
for (ip = v.begin(); ip != v.end(); ++ip) {
cout << *ip << " ";
}
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;
}
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;
}
The factorial of a positive integer n is equal to 1*2*3*...n. In program, user enters a positive integer. Then the "factorial" of that number is "computed and displayed" in the screen. Here
In computer science, a "self-balancing" binary search tree is any "node-based" binary search tree that automatically keeps its height small in the face of arbitrary item insertions & item
Program has 'three functions' which receives 2 pointers reference. Three functions returns int, float and double sum of numbers. So this c++ tutorial use the following concepts. Write
If the reversed integer is equal to the integer then, that number is a palindrome if not that number is not a palindrome. In program, use is asked to enter a 'positive number' which is