C++ Programming Code Examples
C++ > Algorithms Code Examples
Job Sequencing with Deadlines while Maximizing Profits
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* Job Sequencing with Deadlines while Maximizing Profits */
#include<iostream>
#include<list>
using namespace std;
class node{
public:
int d,p,t;
bool operator < (node n)
{
if(p<n.p)
return 1;
else
return 0;
}
};
int main()
{
int d,p,t,i,profit,min,n;
list<node> lst;
node pt;
cout<<"Enter no of entries
";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"enter data(p,d,t)
";
cin>>p>>d>>t;
pt.d=d;
pt.p=p;
pt.t=t;
lst.push_back(pt);
}
int maxd=0;
lst.sort();
lst.reverse();
cout<<"
sorted list
";
list <node> :: iterator itr=lst.begin();
while(itr!=lst.end()){
pt=*itr;
if(maxd<pt.d) maxd=pt.d;
cout<<pt.p<<endl<<pt.d<<endl<<pt.t<<endl<<endl;
itr++;
}
//cout<<" max deadline "<<maxd<<endl;
itr=lst.begin();
profit=0;
while(itr!=lst.end())
{
pt=*itr;
if(pt.d>=pt.t)
min=pt.t;
else
min=pt.d;
if(maxd>=min)
profit+=min*pt.p;
else
profit+=maxd*pt.p;
itr++;maxd=maxd-min;
}
cout<<"profit is : "<<profit<<endl;
return 0;
}
List Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the list container. The past-the-end element is the theoretical element that would follow the last element in the list 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 list::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as list::begin.
Syntax for List end() Function in C++
#include <list>
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
23
24
25
26
27
28
29
30
31
32
33
34
35
/* returns a random access iterator which points to the last element of the list by std::list::end() function code example */
// CPP program to illustrate the list::end() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating a list
list<int> demoList;
// Add elements to the List
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
// using end() to get iterator
// to past the last element
list<int>::iterator it = demoList.end();
// This will not print the last element
cout << "Returned iterator points to : " << *it << endl;
// Using end() with begin() as a range to
// print all of the list elements
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
return 0;
}
Standard Output Stream (cout) in C++
The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.
Syntax for cout in C++
cout << var_name;
//or
cout << "Some String";
<<
is the insertion operator
var_name
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc.
The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output".
The cout object is used along with the insertion operator << in order to display a stream of characters.
The << operator can be used more than once with a combination of variables, strings, and manipulators.
cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* standard output stream (cout) in C++ language */
#include <iostream>
using namespace std;
int main() {
string str = "Do not interrupt me";
char ch = 'm';
// use cout with write()
cout.write(str,6);
cout << endl;
// use cout with put()
cout.put(ch);
return 0;
}
Constructors in C++ Language
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure.
Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object.
Whereas, Destructor on the other hand is used to destroy the class object.
• Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
Syntax for Default Constructor in C++
class_name(parameter1, parameter2, ...)
{
// constructor Definition
}
Syntax for Parameterized Constructor in C++
class class_name
{
public:
class_name(variables) //Parameterized constructor declared.
{
}
};
Syntax for Copy Constructors in C++
classname (const classname &obj) {
// body of constructor
}
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
44
45
46
/* A constructor is a special type of member function that is called automatically when an object is created. In C++, a constructor has the same name as that of the class and it does not have a return type. */
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// initialize variables with parameterized constructor
Wall(double len, double hgt) {
length = len;
height = hgt;
}
// copy constructor with a Wall object as parameter
// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
double calculateArea() {
return length * height;
}
};
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);
// copy contents of wall1 to wall2
Wall wall2 = wall1;
// print areas of wall1 and wall2
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();
return 0;
}
List Library begin() Function in C++
Return iterator to beginning. Returns an iterator pointing to the first element in the list container. Notice that, unlike member list::front, which returns a reference to the first element, this function returns a bidirectional iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced.
begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container.
Syntax for List begin() Function in C++
#include <list>
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
/* returns a random access iterator which points to the first element of the list by std::list::begin() function code example */
// CPP program to illustrate implementation of end() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
// declaration of list container
list<int> mylist{ 1, 2, 3, 4, 5 };
// using end() to print list
for (auto it = mylist.begin(); it !=
mylist.end(); ++it)
cout << ' ' << *it;
return 0;
}
List in C++ Language
List is a popularly used sequence container. Container is an object that holds data of same type. List container is implemented as doubly linked-list, hence it provides bidirectional sequential access to it's data. List doesn't provide fast random access, it only supports sequential access in both directions. List allows insertion and deletion operation anywhere within a sequence in constant time.
Elements of list can be scattered in different chunks of memory. Container stores necessary information to allow sequential access to it's data. Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by internal allocator. Zero sized lists are also valid. In that case list.begin() and list.end() points to same location. But behavior of calling front() or back() is undefined. To define the std::list, we have to import the <list> header file.
Definition Syntax for Lists in C++
template < class Type, class Alloc =allocator<T> > class list;
T
Defines the type of element contained. You can substitute T by any data type, even user-defined types.
Alloc
Defines the type of the allocator object. This uses the allocator class template by default. It's value-dependent and uses a simple memory allocation model.
• List is a contiguous container while vector is a non-contiguous container i.e list stores the elements on a contiguous memory and vector stores on a non-contiguous memory.
• Insertion and deletion in the middle of the vector is very costly as it takes lot of time in shifting all the elements. Linklist overcome this problem and it is implemented using list container.
• List supports a bidirectional and provides an efficient way for insertion and deletion operations.
• Traversal is slow in list as list elements are accessed sequentially while vector supports a random access.
Following member types can be used as parameters or return type by member functions:
• value_type T (First parameter of the template)
• allocator_type Alloc (Second parameter of the template)
• reference value_type&
• const_reference const value_type&
• pointer value_type*
• const_pointer const value_type*
• iterator a random access iterator to value_type
• const_iterator a random access iterator to const value_type
• reverse_iterator std::reverse_iterator <iterator>
• const_reverse_iterator std::reverse_iterator <const_iterator>
• size_type size_t
• difference_type ptrdiff_t
C++ List Member Functions
• insert(): It inserts the new element before the position pointed by the iterator.
• push_back(): It adds a new element at the end of the vector.
• push_front(): It adds a new element to the front.
• pop_back(): It deletes the last element.
• pop_front(): It deletes the first element.
• empty(): It checks whether the list is empty or not.
• size(): It finds the number of elements present in the list.
• max_size(): It finds the maximum size of the list.
• front(): It returns the first element of the list.
• back(): It returns the last element of the list.
• swap(): It swaps two list when the type of both the list are same.
• reverse(): It reverses the elements of the list.
• sort(): It sorts the elements of the list in an increasing order.
• merge(): It merges the two sorted list.
• splice(): It inserts a new list into the invoking list.
• unique(): It removes all the duplicate elements from the list.
• resize(): It changes the size of the list container.
• assign(): It assigns a new element to the list container.
• emplace(): It inserts a new element at a specified position.
• emplace_back(): It inserts a new element at the end of the vector.
• emplace_front(): It inserts a new element at the beginning of the list.
Non-member overloaded functions
operator== Tests whether two lists are equal or not.
2 operator!= Tests whether two lists are equal or not.
3 operator< Tests whether first list is less than other or not.
4 operator<= Tests whether first list is less than or equal to other or not.
5 operator> Tests whether first list is greater than other or not.
6 operator>= Tests whether first list is greater than or equal to other or not.
7 swap Exchanges the contents of two list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* using lists in C++ language simple code example */
#include <iostream>
#include <list>
using namespace std;
int main(void) {
list<int> l;
list<int> l1 = { 10, 20, 30 };
list<int> l2(l1.begin(), l1.end());
list<int> l3(move(l1));
cout << "Size of list l: " << l.size() << endl;
cout << "List l2 contents: " << endl;
for (auto it = l2.begin(); it != l2.end(); ++it)
cout << *it << endl;
cout << "List l3 contents: " << endl;
for (auto it = l3.begin(); it != l3.end(); ++it)
cout << *it << endl;
return 0;
}
List Library push_back() Function in C++
Add element at the end. Adds a new element at the end of the list container, after its current last element. The content of val is copied (or moved) to the new element. This effectively increases the container size by one.
The list:push_back() function in C++ STL is used to add a new element to an existing list container. It takes the element to be added as a parameter and adds it to the list container.
Syntax for List push_back() Function in C++
#include <list>
void push_back (const value_type& val);
void push_back (value_type&& val);
val
Value to be copied (or moved) to the new element. Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T).
This function accepts a single parameter which is mandatory value. This refers to the element needed to be added to the list, list_name.
This function does not return any value.
The storage for the new elements is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Complexity
Constant
Iterator validity
No changes
Data races
The container is modified.
No existing contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
If allocator_traits::construct is not supported with val as argument, it causes 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
/* list::push_back() function is used to push elements into a list from the back. The new value is inserted into the list at the end, after the current last element and the container size is increased by 1.*/
// CPP program code example to illustrate application Of push_back() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> mylist{};
mylist.push_back(7);
mylist.push_back(89);
mylist.push_back(45);
mylist.push_back(6);
mylist.push_back(24);
mylist.push_back(58);
mylist.push_back(43);
// list becomes 7, 89, 45, 6, 24, 58, 43
// Sorting function
mylist.sort();
for (auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}
Standard Input Stream (cin) in C++
The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.
Syntax for Standard Input Stream (cin) in C++
cin >> var_name;
>>
is the extraction operator.
var_name
is usually a variable, but can also be an element of containers like arrays, vectors, lists, etc.
The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input".
The cin object is used along with the extraction operator >> in order to receive a stream of characters.
The >> operator can also be used more than once in the same statement to accept multiple inputs.
The cin object can also be used with other member functions such as getline(), read(), etc. Some of the commonly used member functions are:
• cin.get(char &ch): Reads an input character and stores it in ch.
• cin.getline(char *buffer, int length): Reads a stream of characters into the string buffer, It stops when:
it has read length-1 characters or
when it finds an end-of-line character '\n' or the end of the file eof.
• cin.read(char *buffer, int n): Reads n bytes (or until the end of the file) from the stream into the buffer.
• cin.ignore(int n): Ignores the next n characters from the input stream.
• cin.eof(): Returns a non-zero value if the end of file (eof) is reached.
The prototype of cin as defined in the iostream header file is: extern istream cin; The cin object in C++ is an object of class istream. It is associated with the standard C input stream stdin.
The cin object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed.
After the cin object is constructed, cin.tie() returns &cout. This means that any formatted input operation on cin forces a call to cout.flush() if any characters are pending for output.
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
/* Standard Input Stream (cin) in C++ language */
// cin with Member Functions
#include <iostream>
using namespace std;
int main() {
char name[20], address[20];
cout << "Name: ";
// use cin with getline()
cin.getline(name, 20);
cout << "Address: ";
cin.getline(address, 20);
cout << endl << "You entered " << endl;
cout << "Name = " << name << endl;
cout << "Address = " << address;
return 0;
}
Assignment Operators in C++
As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators.
Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:
=
Simple assignment operator. Assigns values from right side operands to left side operand
+=
Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
-=
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.
*=
Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
/=
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.
%=
Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.
<<=
Left shift AND assignment operator.
>>=
Right shift AND assignment operator.
&=
Bitwise AND assignment operator.
^=
Bitwise exclusive OR and assignment operator.
|=
Bitwise inclusive OR and assignment operator.
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
/* Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. */
// C++ program to demonstrate working of Assignment operators
#include <iostream>
using namespace std;
int main()
{
// Assigning value 10 to a
// using "=" operator
int a = 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by adding 10 to a
// using "+=" operator
a += 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by subtracting 10 from a
// using "-=" operator
a -= 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by multiplying 10 to a
// using "*=" operator
a *= 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by dividing 10 from a
// using "/=" operator
a /= 10;
cout << "Value of a is "<<a<<"\n";
return 0;
}
Classes and Objects in C++ Language
The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.
C++ Class Definitions
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows:
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
Define C++ Objects
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box:
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Accessing the Data Members
The public data members of objects of a class can be accessed using the direct member access operator (.).
It is important to note that private and protected members can not be accessed directly using direct member access operator (.).
Classes and Objects in Detail
There are further interesting concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below:
• Class Member Functions: A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.
• Class Access Modifiers: A class member can be defined as public, private or protected. By default members would be assumed as private.
• Constructor & Destructor: A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.
• Copy Constructor: The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
• Friend Functions: A friend function is permitted full access to private and protected members of a class.
• Inline Functions: With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function.
• this Pointer: Every object has a special pointer this which points to the object itself.
• Pointer to C++ Classes: A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.
• Static Members of a Class: Both data members and function members of a class can be declared as static.
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
44
45
46
/* using public and private in C++ Class */
// Program to illustrate the working of
// public and private in C++ Class
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
// function to initialize private variables
void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
// create object of Room class
Room room1;
// pass the values of private variables as arguments
room1.initData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
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;
}
List Library sort() Function in C++
Sort elements in container. Sorts the elements in the list, altering their position within the container. The C++ function std::list::sort() sorts the elements of the list in ascending order. The order of equal elements is preserved. It uses operator< for comparison.
The sorting is performed by applying an algorithm that uses either operator< (in version (1)) or comp (in version (2)) to compare elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without considering its reflexiveness).
The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative order they had before the call.
The entire operation does not involve the construction, destruction or copy of any element object. Elements are moved within the container.
Syntax for List sort() Function in C++
#include <list>
//(1)
void sort();
//(2)
template <class Compare>
void sort (Compare comp);
comp
Binary predicate that, taking two values of the same type of those contained in the list, returns true if the first argument goes before the second argument in the strict weak ordering it defines, and false otherwise. This shall be a function pointer or a function object.
This function does not return any value.
Complexity
Approximately NlogN where N is the container size.
Iterator validity
No changes
Data races
The container is modified. All contained elements are accessed (but not modified). Concurrently iterating through the container is not safe.
Exception safety
Basic guarantee: if an exception is thrown, the container is in a valid state. It throws if the comparison or the moving operation of any element throws.
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
/* C++ List sort() function arranges the elements of a given list in an increasing order. It does not involve in any construction and destruction of elements. Elements are only moved within the container. */
/* sort the elements of the list container list::sort function code example. */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{33, 7, 45, -12, 25, 75};
list<int>::iterator it;
cout<<"MyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
//sort elements of the list
MyList.sort();
cout<<"\nMyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
return 0;
}
List Library reverse() Function in C++
Reverse the order of elements. Reverses the order of the elements in the list container. The list::reverse() is a built-in function in C++ STL which is used to reverse a list container.
It reverses the order of elements in the list container.
Syntax for List reverse() Function in C++
#include <list>
void reverse() noexcept;
Complexity
Linear in list size
Iterator validity
No changes
Data races
The container is modified. No contained elements are accessed: concurrently accessing or modifying them is safe, although iterating through the container is not.
Exception safety
No-throw guarantee: this member function never throws exceptions.
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
/* list::reverse() is an inbuilt function in C++ STL which is declared in header file. reverse() is used to reverse the list container, means the last element of the list becomes the first element of the list. */
/* reverse the order of elements of the list container by list::reverse function code example. */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{10, 20, 30, 40, 50};
list<int>::iterator it;
cout<<"MyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
//Reverse the order of all elements of the list
MyList.reverse();
cout<<"\nMyList contains: ";
for(it = MyList.begin(); it != MyList.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;
}
Standard end line (endl) in C++
A predefined object of the class called iostream class is used to insert the new line characters while flushing the stream is called endl in C++. This endl is similar to \n which performs the functionality of inserting new line characters but it does not flush the stream whereas endl does the job of inserting the new line characters while flushing the stream. Hence the statement cout<<endl; will be equal to the statement cout<< '\n' << flush; meaning the new line character used along with flush explicitly becomes equivalent to the endl statement in C++.
Syntax for end line (endl) in C++
cout<< statement to be executed <<endl;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Standard end line (endl) in C++ language */
//The header file iostream is imported to enable us to use cout in the program
#include <iostream>
//a namespace called std is defined
using namespace std;
//main method is called
int main( )
{
//cout is used to output the statement
cout<< "Welcome to ";
//cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream
cout<< "C#"<<endl;
//cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream
cout<< "Learning is fun"<<endl;
}
While Loop Statement in C++
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop.
The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
Syntax for While Loop Statement in C++
while (condition) {
// body of the loop
}
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
/* While Loop Statement in C++ language */
// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0) {
// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum is " << sum << endl;
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;
}
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;
}
If Else Statement in C++
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++:
• if statement,
• if...else statement,
• if...else if...else statement,
Syntax for If Statement in C++
if (condition) {
// body of if statement
}
Syntax for If...Else Statement
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
Syntax for If...Else...Else If Statement in C++
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Syntax for If Else If Ladder in C++
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* If Else Statement in C++ Language */
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
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;
}
Method that implements the basic primality test. If witness doesn't return 1, n is definitely composite. Do this by computing a^i (mod n) and looking for "non-trivial" square roots of 1
"Multiply two Signed numbers" using Booth's algorithm. Booth's multiplication algorithm is a multiplication algorithm that multiplies two signed 'binary numbers' in two's complement
To encrypt & decrypt file content in C++, you have to enter the file name with extension to encrypt & decrypt the content present inside the file. Now open that file using the function