C++ Programming Code Examples
C++ > Code Snippets Code Examples
Making a Sequence of Random Numbers
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
/* Making a Sequence of Random Numbers */
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
template <class T>
void print(T& c){
for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
std::cout << *i << endl;
}
}
int main( )
{
vector<int> random( 8 );
// fill the container with random numbers
generate( random.begin(), random.end(), rand );
print( random );
}
Function Templates in C++
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.
Syntax for Function Templates in C++
template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Ttype
a placeholder name
class
specify a generic type
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.
• Generic functions use the concept of a function template. Generic functions define a set of operations that can be applied to the various types of data.
• The type of the data that the function will operate on depends on the type of the data passed as a parameter.
• For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats.
• A Generic function is created by using the keyword template. The template defines what function will do.
Function templates with multiple parameters:
We can use more than one generic type in the template function by using the comma to separate the list.
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of 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
/* function templates in C++ language */
/* adding two numbers using function templates */
#include <iostream>
using namespace std;
template <typename T>
T add(T num1, T num2) {
return (num1 + num2);
}
int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << endl;
// calling with double parameters
result2 = add<double>(2.2, 3.3);
cout << "2.2 + 3.3 = " << result2 << endl;
return 0;
}
Namespaces in C++ Language
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc.
Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name {
// code declarations
}
name::code; // code could be variable or function.
Using Directive
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files.
So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one:
namespace namespace_name {
// code declarations
}
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space as follows:
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
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
/* namespaces in C++ language */
// A C++ code to demonstrate that we can define
// methods outside namespace.
#include <iostream>
using namespace std;
// Creating a namespace
namespace ns
{
void display();
class happy
{
public:
void display();
};
}
// Defining methods of namespace
void ns::happy::display()
{
cout << "ns::happy::display()\n";
}
void ns::display()
{
cout << "ns::display()\n";
}
// Driver code
int main()
{
ns::happy obj;
ns::display();
obj.display();
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;
}
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;
}
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;
}
#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;
}
For Loop Statement in C++
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.
Syntax of For Loop Statement in C++
for (initialization; condition; update) {
// body of-loop
}
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition.
A new range-based for loop was introduced to work with collections such as arrays and 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
/* For Loop Statement in C++ Language */
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers
#include <iostream>
using namespace std;
int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
sum += i;
}
cout << "Sum = " << sum << endl;
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;
}
Class Templates in C++
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.
Declaration for Class Template in C++
template <class T>
class className {
private:
T var;
... .. ...
public:
T functionName(T arg);
... .. ...
};
T
template argument
var
a member variable
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.
Creating a class template object:
Once we've declared and defined a class template, we can create its objects in other classes or functions (such as the main() function) with the following syntax:
className<dataType> classObject;
template <class T>
class ClassName {
... .. ...
// Function prototype
returnType functionName();
};
// Function definition
template <class T>
returnType ClassName<T>::functionName() {
// code
}
template <class T, class U, class V = int>
class ClassName {
private:
T member1;
U member2;
V member3;
... .. ...
public:
... .. ...
};
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
/* Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function. */
#include <iostream>
using namespace std;
template <typename T>
class Array {
private:
T *ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T>
Array<T>::Array(T arr[], int s) {
ptr = new T[s];
size = s;
for(int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print() {
for (int i = 0; i < size; i++)
cout<<" "<<*(ptr + i);
cout<<endl;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
Array<int> a(arr, 5);
a.print();
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;
}
generate() Function in C++
The generate functions assigns random values provided by calling the generator function 'gen' to the elements in the range [begin, end). Notice that begin is included in the range but end is NOT included.
C++ Algorithm generate() function is used to assign the value generated by a function object to each element in a range. The generator function is defined by the user and it is called successively for assigning the numbers.
Syntax for generate() Function in C++
#include <algorithm>
template <class ForwardIterator, class Generator>
void generate (ForwardIterator first, ForwardIterator last, Generator gen);
first
A forward iterator pointing the position of the first element in the range to which values are to be assigned.
last
A forward iterator pointing the position one past the final element in the range to which values are to be assigned.
Forward iterators to the initial and final positions in a sequence. The range affected 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.
gen
A function object with no arguments that is used to generate the values to be assigned to each of the elements in the range. Generator function that is called with no arguments and returns some value of a type convertible to those pointed by the iterators. This can either be a function pointer or a function object.
This function does not return any value.
Complexity
Linear in the distance between first and last: Calls gen and performs an assignment for each element.
Data races
The objects in the range [first,last) are modified (each object is accessed exactly once).
Exceptions
Throws if any of gen, 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
/* generate values for range with function by generate() function code example */
// C++ program to demonstrate generate function in STL
#include <bits/stdc++.h>
using namespace std;
// function to generate random numbers in range [0-999] :
int randomize()
{
return (rand() % 1000);
}
int main ()
{
// for different values each time we run the code
srand(time(NULL));
vector<int> vect(10); // declaring the vector
// Fill all elements using randomize()
generate(vect.begin(), vect.end(), randomize);
// displaying the content of vector
for (int i=0; i<vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
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
To find the HCF ('Highest Common Factor') or GCD (Greatest Common Divisor) of 2 or more numbers, make prime factors of the numbers and choose the common prime factors. Then
Program demonstrates implementation of max-flow_min-cut_theorem. So returns true if there is a 'path from source' 's' to sink 't' in residual graph. Also fills parent[] to store the
To write a "Multiline Comment" you have to write "/*" at the start of the Comment. After this you can write as many number of lines of description. When you are done with writing
c contains the number of columns for each of the n matrices. c[ 0 ] is the number of rows in matrix 1. Minimum number of multiplications is left in m[1][n]. Actual ordering is computed
In c++ sort pogram sample, count the number of 'occurrences' of each element. And store it in the Array of size same as the range of data input. Use element value to refer the counter