Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > Code Snippets Code Examples

Make vector large enough to hold all value

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
/* Make vector large enough to hold all value */ #include <algorithm> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> using namespace std; class PC { public: enum part { keyboard, mouse, monitor }; PC( part a_part = PC::keyboard, int id = 0 ); bool operator<( const PC& rhs ) const; void print() const; private: part part_; int id_; }; inline PC::PC( part a_part, int id ) : part_( a_part ), id_( id ){} inline bool PC::operator<( const PC& rhs ) const{ return id_ < rhs.id_; } void PC::print() const { string component; if( part_ == keyboard ) component = "keyboard"; else if( part_ == mouse ) component = "mouse"; else component = "monitor"; cout << "ID: " << setw( 8 ) << left << id_ << " PC: " << component << endl; } int main( ) { list<PC> listA; listA.push_back( PC( PC::keyboard, 3 ) ); listA.push_back( PC( PC::mouse, 1 ) ); listA.push_back( PC( PC::monitor, 9 ) ); listA.push_back( PC( PC::keyboard, 2 ) ); listA.push_back( PC( PC::monitor, 8 ) ); list<PC> inspector_B( listA ); inspector_B.front() = PC( PC::mouse, 6 ); inspector_B.back() = PC( PC::monitor, 1 ); // must sort before using set algorithms listA.sort(); inspector_B.sort(); vector<PC> result; result.resize( listA.size() + inspector_B.size() ); }
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; }
Iomanip Library setw() Function in C++
Set field width. Sets the field width to be used on output operations. The C++ function std::setw behaves as if member width were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams). It is used to sets the field width to be used on output operations. This manipulator is declared in header <iomanip>.
Syntax for setw() Function in C++
#include <iomanip> /*undefined*/ setw (int n);
n
Number of characters to be used as field width. This method accepts n as a parameter which is the integer argument corresponding to which the field width is to be set. This function returns an object of unspecified type. The setw function should only be used as a stream manipulator. Like the different functions in C++ the setw() function helps in setting the field width which will be used on output operations. This function will take the member width whenever it will be called as an argument. It will need a stream where this field will be inserted or manipulated. This function will set the width parameter of the stream out or stream in to exactly n times. It will take the parameter which will be the new value of the width to which this has to be set.
Data races
The stream object on which it is inserted/extracted is modified. Concurrent access to the same stream object may introduce data races.
Exception safety
Basic guarantee: if an exception is thrown, the stream is in a valid state.
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
/* specify the minimum number of character positions on the output field a variable will consume by setw function() code example. */ // C++ code to demonstrate the working of setw() function #include <iomanip> #include <ios> #include <iostream> using namespace std; int main() { // Initializing the integer int num = 50; cout << "Before setting the width: \n" << num << endl; // Using setw() cout << "Setting the width" << " using setw to 5: \n" << setw(5); cout << num << 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 }
To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows:
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 } }
• Namespace is a feature added in C++ and not present in C. • A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. • Namespace declarations appear only at global scope. • Namespace declarations can be nested within another namespace. • Namespace declarations don't have access specifiers. (Public or private) • No need to give semicolon after the closing brace of definition of namespace. • We can split the definition of namespace over several units.
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; }
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;
The type parameter <T> specifies the type of the vector. It can be any primitive data type such as int, char, float, etc.
Initialization for Vectors in C++
// Vector initialization method 1 // Initializer list vector<int> vector1 = {1, 2, 3, 4, 5};
We are initializing the vector by providing values directly to the vector. vector1 is initialized with values 1, 2, 3, 4, 5.
// Vector initialization method 2 vector<int> vector3(5, 12);
Here, 5 is the size of the vector and 8 is the value. This code creates an int vector with size 5 and initializes the vector with the value of 8. So, the vector is equivalent to
vector<int> vector2 = {8, 8, 8, 8, 8};
The vector class provides various methods to perform different operations on vectors. Add Elements to a Vector: To add a single element into a vector, we use the push_back() function. It inserts an element into the end of the vector. Access Elements of a Vector: In C++, we use the index number to access the vector elements. Here, we use the at() function to access the element from the specified index. Change Vector Element: We can change an element of the vector using the same at() function. Delete Elements from C++ Vectors: To delete a single element from a vector, we use the pop_back() function. In C++, the vector header file provides various functions that can be used to perform different operations on a vector. • size(): returns the number of elements present in the vector. • clear(): removes all the elements of the vector. • front(): returns the first element of the vector. • back(): returns the last element of the vector. • empty(): returns 1 (true) if the vector is empty. • capacity(): check the overall size of a vector. Vector iterators are used to point to the memory address of a vector element. In some ways, they act like pointers.
Syntax for Vector Iterators in C++
vector<T>::iterator iteratorName;
We can initialize vector iterators using the begin() and end() functions. The begin() function returns an iterator that points to the first element of the vector. The end() function points to the theoretical element that comes after the final element of the vector.
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 resize() Function in C++
Change size. Resizes the container so that it contains n elements. The vector is a very useful class of C++ for creating the dynamic array. The size of the vector can be changed at any time to solve any programming problem. Many built-in functions exist in C++ for doing the different types of tasks in a vector container. The resize() function is one of them. It is used to change the size of the vector. The vector size can be increased or decreased by using this function.
Syntax for Vector resize() Function in C++
#include <vector> void resize (size_type n); void resize (size_type n, const value_type& val);
n
New container size, expressed in number of elements. Member type size_type is an unsigned integral type.
val
Object whose content is copied to the added elements in case that n is greater than the current container size. If not specified, the default constructor is used instead. Member type value_type is the type of the elements in the container, defined in vector as an alias of the first template parameter (T). This function does not return any value. If a reallocation happens, the storage 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). If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them). If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized. If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place. Notice that this function changes the actual content of the container by inserting or erasing elements from it.
Complexity
Linear on the number of elements inserted/erased (constructions/destructions). If a reallocation happens, the reallocation is itself up to linear in the entire vector size.
Iterator validity
In case the container shrinks, all iterators, pointers and references to elements that have not been removed remain valid after the resize and refer to the same elements they were referring to before the call. If the container expands, the end iterator is invalidated and, if it has to reallocate storage, all iterators, pointers and references related to this container are also invalidated.
Data races
The container is modified. If a reallocation happens, all contained elements are modified. Otherwise, none of the elements before n is accessed, and concurrently accessing or modifying them is safe.
Exception safety
If n is less than or equal to the size of the container, the function never throws exceptions (no-throw guarantee). If n is greater and a reallocation happens, there are no changes in the container in case of exception (strong guarantee) if the type of the elements is either copyable or no-throw moveable. Otherwise, if an exception is thrown, the container is left with a valid state (basic guarantee).
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
/* resize the container by specified number of elements (n) by vector::resize function code example */ // resizing of the vector #include <iostream> #include <vector> using namespace std; int main() { vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(4); cout << "Contents of vector after resizing:" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0; }
Inline Functions in C++
Inline function is one of the important feature of C++. So, let's first understand why inline functions are used and what is the purpose of inline function? When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually execute the function's code. This overhead occurs for small functions because execution time of small function is less than the switching time. C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency if it is small.
Syntax for Defining the Function Inline
inline return-type function-name(parameters) { // function code }
Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request for inlining. Compiler may not perform inlining in such circumstances like: • If a function contains a loop. (for, while, do-while) • If a function contains static variables. • If a function is recursive. • If a function return type is other than void, and the return statement doesn't exist in function body. • If a function contains switch or goto statement.
Inline Functions Provide Following Advantages
• Function call overhead doesn't occur. • It also saves the overhead of push/pop variables on the stack when function is called. • It also saves overhead of a return call from a function. • When you inline a function, you may enable compiler to perform context specific optimization on the body of function. Such optimizations are not possible for normal function calls. Other optimizations can be obtained by considering the flows of calling context and the called context. • Inline function may be useful (if it is small) for embedded systems because inline can yield less code than the function call preamble and return.
Inline Function Disadvantages
• The added variables from the inlined function consumes additional registers, After in-lining function if variables number which are going to use register increases than they may create overhead on register variable resource utilization. This means that when inline function body is substituted at the point of function call, total number of variables used by the function also gets inserted. So the number of register going to be used for the variables will also get increased. So if after function inlining variable numbers increase drastically then it would surely cause an overhead on register utilization. • If you use too many inline functions then the size of the binary executable file will be large, because of the duplication of same code. • Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of instruction fetch from that of cache memory to that of primary memory. • Inline function may increase compile time overhead if someone changes the code inside the inline function then all the calling location has to be recompiled because compiler would require to replace all the code once again to reflect the changes, otherwise it will continue with old functionality. • Inline functions may not be useful for many embedded systems. Because in embedded systems code size is more important than speed. • Inline functions might cause thrashing because inlining might increase size of the binary executable file. Thrashing in memory causes performance of computer to degrade.
Inline Function And Classes
It is also possible to define the inline function inside the class. In fact, all the functions defined inside the class are implicitly inline. Thus, all the restrictions of inline functions are also applied here. If you need to explicitly declare inline function in the class then just declare the function inside the class and define it outside the class using inline keyword.
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
/* If make a function as inline, then the compiler replaces the function calling location with the definition of the inline function at compile time. Any changes made to an inline function will require the inline function to be recompiled again because the compiler would need to replace all the code with a new code; otherwise, it will execute the old functionality. */ #include <iostream> using namespace std; class operation { int a,b,add,sub,mul; float div; public: void get(); void sum(); void difference(); void product(); void division(); }; inline void operation :: get() { cout << "Enter first value:"; cin >> a; cout << "Enter second value:"; cin >> b; } inline void operation :: sum() { add = a+b; cout << "Addition of two numbers: " << a+b << "\n"; } inline void operation :: difference() { sub = a-b; cout << "Difference of two numbers: " << a-b << "\n"; } inline void operation :: product() { mul = a*b; cout << "Product of two numbers: " << a*b << "\n"; } inline void operation ::division() { div=a/b; cout<<"Division of two numbers: "<<a/b<<"\n" ; } int main() { cout << "Program using inline function\n"; operation s; s.get(); s.sum(); s.difference(); s.product(); s.division(); return 0; }
List Library size() Function in C++
Return size. Returns the number of elements in the list container. list::size() is an inbuilt function in C++ STL which is declared in <list> header file. size() returns the size of a particular list container. In other words it returns the number of elements which are present in a list container.
Syntax for List size() Function in C++
#include <list> size_type size() const noexcept;
This function does not accept any parameter. Function returns the number of elements in the container. Member type size_type is an unsigned integral type.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them is safe.
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
/* list::size() function in C++ is used to find the number of elements present in a list container. That is, it is used to find the size of the list container. */ /* find the number of elements present in the list by size() function code example. */ #include <iostream> #include <list> using namespace std; int main (){ list<int> MyList{10, 20, 30, 40, 50}; cout<<"List size is: "<<MyList.size()<<"\n"; cout<<"Three elements are added in the List.\n"; MyList.push_back(60); MyList.push_back(70); MyList.push_back(80); cout<<"Now, List size is: "<<MyList.size()<<"\n"; return 0; }
List Library front() Function in C++
Access first element. Returns a reference to the first element in the list container. The C++ list::front function returns a reference to the first element of the list. Please note that, Unlike the list::begin function, which returns the iterator pointing to the first element, it returns the a direct reference to the same element of the list. Unlike member list::begin, which returns an iterator to this same element, this function returns a direct reference. Calling this function on an empty container causes undefined behavior.
Syntax for List front() Function in C++
#include <list> reference front(); const_reference front() const;
No parameter is required. Function returns a reference to the first element in the list container. If the list object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference. Member types reference and const_reference are the reference types to the elements of the container (see list member types).
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). The first element is potentially accessed or modified by the caller. Concurrently accessing or modifying other elements is safe.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, 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
/* The list::front() is a built-in function in C++ STL which is used to return a reference to the first element in a list container. Unlike the list::begin() function, this function returns a direct reference to the first element in the list container. */ /* return the first element of the list by front() function code example. */ #include <iostream> #include <list> using namespace std; int main (){ list<int> MyList{10, 20, 30, 40, 50}; cout<<"The first element of MyList is: "; cout<<MyList.front(); cout<<"\n\nAdd 100 to the first element of the MyList.\n"; MyList.front() = MyList.front() + 100; cout<<"Now, The first element of MyList is: "; cout<<MyList.front(); 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 }
The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
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; }
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 }
• Parameterized Constructor: In C++, a constructor with parameters is known as a parameterized constructor. This is the preferred method to initialize member data. These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.
Syntax for Parameterized Constructor in C++
class class_name { public: class_name(variables) //Parameterized constructor declared. { } };
• Copy Constructors: These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object.
Syntax for Copy Constructors in C++
classname (const classname &obj) { // body of 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. The copy constructor is used to - • Initialize one object from another of the same type. • Copy an object to pass it as an argument to a function. • Copy an object to return it from a function. If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here.
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; }
Enumeration (or enum) in C++
Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword "enum" is used to declare an enumeration. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly. C++ Enums can be thought of as classes that have fixed set of constants.
Syntax for enum in C++
enum enum_name{const1, const2, ....... };
enum_name
Any name given by user
const1, const2
These are values of type flag The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows
enum colors{red, black}; enum suit{heart, diamond=8, spade=3, club};
Points to remember for C++ Enum: • enum improves type safety • enum can be easily used in switch • enum can be traversed • enum can have fields, constructors and methods • enum may implement many interfaces but cannot extend any class because it internally extends Enum class
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
/* Enum is a user defined data type where we specify a set of values for a variable and the variable can only take one out of a small set of possible values. We use enum keyword to define a Enumeration. */ #include <bits/stdc++.h> using namespace std; int main() { // Defining enum Gender enum Gender { Male, Female }; // Creating Gender type variable Gender gender = Male; switch (gender) { case Male: cout << "Gender is Male"; break; case Female: cout << "Gender is Female"; break; default: cout << "Value can be Male or Female"; } 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"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }
List Library back() Function in C++
Access last element. Returns a reference to the last element in the list container. list::back() is an inbuilt function in C++ STL which is declared in header file. back() is used to refer to the last element of the list container. This function returns a direct reference to the last element only. When the list is empty then the function performs an undefined behaviour. Unlike member list::end, which returns an iterator just past this element, this function returns a direct reference. Calling this function on an empty container causes undefined behavior.
Syntax for List back() Function in C++
#include <list> reference back(); const_reference back() const;
No parameter is required. Function returns a reference to the last element in the list. If the list object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference. Member types reference and const_reference are the reference types to the elements of the list (see member types).
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). The last element is potentially accessed or modified by the caller. Concurrently accessing or modifying other elements is safe.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, 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
/* The list::back() function in C++ STL returns a direct reference to the last element in the list container. This function is different from the list::end() function as the end() function returns only the iterator to the last element. */ /* Return the last element of the list by List back() function code example. */ #include <iostream> #include <list> using namespace std; int main (){ list<int> MyList{10, 20, 30, 40, 50}; cout<<"The last element of MyList is: "; cout<<MyList.back(); cout<<"\n\nAdd 100 to the last element of the MyList.\n"; MyList.back() = MyList.back() + 100; cout<<"Now, The last element of MyList is: "; cout<<MyList.back(); return 0; }
If Else If Ladder in C/C++
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax of if...else Ladder in C++
if (Condition1) { Statement1; } else if(Condition2) { Statement2; } . . . else if(ConditionN) { StatementN; } else { Default_Statement; }
In the above syntax of if-else-if, if the Condition1 is TRUE then the Statement1 will be executed and control goes to next statement in the program following if-else-if ladder. If Condition1 is FALSE then Condition2 will be checked, if Condition2 is TRUE then Statement2 will be executed and control goes to next statement in the program following if-else-if ladder. Similarly, if Condition2 is FALSE then next condition will be checked and the process continues. If all the conditions in the if-else-if ladder are evaluated to FALSE, then Default_Statement will be executed.
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
/* write a C program which demonstrate use of if-else-if ladder statement */ /* Program to Print Day Names using Else If Ladder in C++*/ #include <iostream> using namespace std; int main() { int day; cout << "Enter Day Number: "; cin >> day; cout << "Day is "; if (day == 1) cout << "Sunday" << endl; else if (day == 2) cout << "Monday" << endl; else if (day == 3) cout << "Tuesday" << endl; else if (day == 4) cout << "Wednesday" << endl; else if (day == 5) cout << "Thursday" << endl; else if (day == 6) cout << "Friday" << endl; else cout << "Saturday" << endl; 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; }
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; }
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 };
The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.
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
Both of the objects Box1 and Box2 will have their own copy of data members.
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; }


This C++ Program implement "Affine Cipher". The affine cipher is a type of Monoalphabetic Substitution Cipher, wherein each letter in an alphabet is mapped to its numeric equivalent,
C++ Program to generate 'random' numbers using Park-Miller algorithm. general formula of a random number generator (RNG) of this type is: 'X_{k+1} = g X(k) mod n'. To generate
In this, includes the inserting a node, deleting a node, recursive tree traversal, non-recursive Tree Traversal, finding the minimum and the maximum, leftchild, rightchild, copy a tree to