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++ > Visual C++ 5.0 Standard C++ Library Code Examples

The generate n algorithm traverses the range [first, first + n), assigning to each

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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
/* The generate n algorithm traverses the range [first, first + n), assigning to each generate_n */ Header <algorithm> template<class OutputIterator, class Size, class Generator> inline void generate_n(OutputIterator first, Size n, Generator gen) /* The generate_n algorithm traverses the range [first, first + n), assigning to each element the value returned by gen. Note that generate modifies the elements in the specified range. */ Sample // disable warning C4786: symbol greater than 255 character, // okay to ignore #pragma warning(disable: 4786) #include <iostream> #include <vector> #include <algorithm> using namespace std; // return the next Fibonacci number in the // Fibonacci series. int Fibonacci(void) { static int r; static int f1 = 0; static int f2 = 1; r = f1 + f2 ; f1 = f2 ; f2 = r ; return f1 ; } void main() { const int VECTOR_SIZE = 15 ; // Define a template class vector of integers typedef vector<int > IntVector ; //Define an iterator for template class vector of integer typedef IntVector::iterator IntVectorIt ; IntVector Numbers(VECTOR_SIZE) ; //vector containing numbers IntVectorIt start, end, it ; int i ; //Initialize vector Numbers for(i = 0; i < VECTOR_SIZE; i++) Numbers[i] = i * i ; start = Numbers.begin() ; // location of first // element of Numbers end = Numbers.end() ; // one past the location // last element of Numbers cout << "Before calling generate_n" << endl ; // print content of Numbers cout << "Numbers { " ; for(it = start; it != end; it++) cout << *it << " " ; cout << " }\n" << endl ; // fill the specified range with a series of // Fibonacci numbers using the Fibonacci function generate_n(start + 5, Numbers.size() - 5, Fibonacci) ; cout << "After calling generate_n" << endl ; // print content of Numbers cout << "Numbers { " ; for(it = start; it != end; it++) cout << *it << " " ; cout << " }\n" << endl ; } /* Program Output Before calling generate_n Numbers { 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 } After calling generate_n Numbers { 0 1 4 9 16 1 1 2 3 5 8 13 21 34 55 } */
Vector Library begin() Function in C++
Return iterator to beginning. Returns an iterator pointing to the first element in the vector. Notice that, unlike member vector::front, which returns a reference to the first element, this function returns a random access iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. The C++ function std::vector::begin() returns a random access iterator pointing to the first element of the vector.
Syntax for Vector begin() Function in C++
#include <vector> iterator begin() noexcept; const_iterator begin() const noexcept;
This function does not accept any parameter. Function returns an iterator to the beginning of the sequence container. If the vector object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are random access iterator types (pointing to an element and to a const element, respectively).
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* returns a random access iterator pointing to the first element of the vector by std::vector::begin() function code example. */ // CPP program to illustrate implementation of begin() function #include <iostream> #include <string> #include <vector> using namespace std; int main() { // declaration of vector container vector<string> myvector{ "This", "is", "HappyCodings" }; // using begin() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0; }
Static Keyword in C++
Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event. Advantage of C++ static keyword: Memory efficient. Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance is created. C++ Static Field: A field which is declared as static is called static field. Unlike instance field which gets memory each time whenever you create object, there is only one copy of static field created in the memory. It is shared to all the objects. It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee etc. Static variables inside functions: Static variables when used inside function are initialized only once, and then they hold there value even through function calls. These static variables are stored on static storage area , not in stack.
void counter() { static int count=0; cout << count++; } int main(0 { for(int i=0;i<5;i++) { counter(); } }
Static class objects: Static keyword works in the same way for class objects too. Objects declared static are allocated storage in static storage area, and have scope till the end of program. Static objects are also initialized using constructors like other normal objects. Assignment to zero, on using static keyword is only for primitive datatypes, not for user defined datatypes.
class Abc { int i; public: Abc() { i=0; cout << "constructor"; } ~Abc() { cout << "destructor"; } }; void f() { static Abc obj; } int main() { int x=0; if(x==0) { f(); } cout << "END"; }
Static data member in class: Static data members of class are those members which are shared by all the objects. Static data member has a single piece of storage, and is not available as separate copy with each object, like other non-static data members. Static member variables (data members) are not initialied using constructor, because these are not dependent on object initialization. Also, it must be initialized explicitly, always outside the class. If not initialized, Linker will give error.
class X { public: static int i; X() { // construtor }; }; int X::i=1; int main() { X obj; cout << obj.i; // prints value of i }
Static member functions: These functions work for the class as whole rather than for a particular object of a class. It can be called using an object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator.
class X { public: static void f() { // statement } }; int main() { X::f(); // calling member function directly with class name }
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
/* static keyword has different meanings when used with different types simple code example */ // CPP program to illustrate class objects as static #include<iostream> using namespace std; class Happy { int i = 0; public: Happy() { i = 0; cout << "Inside Constructor\n"; } ~Happy() { cout << "Inside Destructor\n"; } }; int main() { int x = 0; if (x==0) { static Happy obj; } cout << "End of main\n"; }
Function Templates in C++
A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values.
Syntax for Function Templates in C++
template < class Ttype> ret_type func_name(parameter_list) { // body of function. }
Ttype
a placeholder name
class
specify a generic type Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration. • Generic functions use the concept of a function template. Generic functions define a set of operations that can be applied to the various types of data. • The type of the data that the function will operate on depends on the type of the data passed as a parameter. • For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats. • A Generic function is created by using the keyword template. The template defines what function will do. Function templates with multiple parameters: We can use more than one generic type in the template function by using the comma to separate the list.
template<class T1, class T2,.....> return_type function_name (arguments of type T1, T2....) { // body of function. }
Overloading a function template: We can overload the generic function means that the overloaded template functions can differ in the parameter list. Generic functions perform the same operation for all the versions of a function except the data type differs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* function templates in C++ language */ /* adding two numbers using function templates */ #include <iostream> using namespace std; template <typename T> T add(T num1, T num2) { return (num1 + num2); } int main() { int result1; double result2; // calling with int parameters result1 = add<int>(2, 3); cout << "2 + 3 = " << result1 << endl; // calling with double parameters result2 = add<double>(2.2, 3.3); cout << "2.2 + 3.3 = " << result2 << endl; return 0; }
Functions in C++
The function in C++ language is also known as procedure or subroutine in other programming languages. To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability. Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check...
Defining a Function in C++
return-type function-name(parameter1, parameter2, ...) { // function-body }
return type
suggests what the function will return. It can be int, char, some pointer or even a class object. There can be functions which does not return anything, they are mentioned with void.
name
Function name is the name of the function, using the function name it is called.
parameters
Parameters are variables to hold values of arguments passed while function is called. A function may or may not contain parameter list.
body
Function body is the part where the code statements are written. Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them: • Call by Value: In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes. • Call by Reference: In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable.
Advantage of Functions
• Code Reusability: By creating functions in C++, you can call it many times. So we don't need to write the same code again and again. • Code optimization: It makes the code optimized, we don't need to write much code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* function with parameters in C++ language */ // program to print a text #include <iostream> using namespace std; // display a number void displayNum(int n1, float n2) { cout << "The int number is " << n1; cout << "The double number is " << n2; } int main() { int num1 = 5; double num2 = 5.5; // calling the function displayNum(num1, num2); 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; }
#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; }
Class Templates in C++
Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration.
Declaration for Class Template in C++
template <class T> class className { private: T var; ... .. ... public: T functionName(T arg); ... .. ... };
T
template argument
var
a member variable T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T. Creating a class template object: Once we've declared and defined a class template, we can create its objects in other classes or functions (such as the main() function) with the following syntax:
className<dataType> classObject;
Defining a class member outside the class template: Suppose we need to define a function outside of the class template. We can do this with the following code:
template <class T> class ClassName { ... .. ... // Function prototype returnType functionName(); }; // Function definition template <class T> returnType ClassName<T>::functionName() { // code }
Notice that the code template <class T> is repeated while defining the function outside of the class. This is necessary and is part of the syntax. C++ class templates with multiple parameters: In C++, we can use multiple template parameters and even use default arguments for those parameters.
template <class T, class U, class V = int> class ClassName { private: T member1; U member2; V member3; ... .. ... public: ... .. ... };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/* Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function. */ #include <iostream> using namespace std; template <typename T> class Array { private: T *ptr; int size; public: Array(T arr[], int s); void print(); }; template <typename T> Array<T>::Array(T arr[], int s) { ptr = new T[s]; size = s; for(int i = 0; i < size; i++) ptr[i] = arr[i]; } template <typename T> void Array<T>::print() { for (int i = 0; i < size; i++) cout<<" "<<*(ptr + i); cout<<endl; } int main() { int arr[5] = {1, 2, 3, 4, 5}; Array<int> a(arr, 5); a.print(); return 0; }
Algorithm Library generate_n() Function in C++
Generate values for sequence with function. Assigns the value returned by successive calls to gen to the first n elements of the sequence pointed by first. C++ Algorithm generate_n() function is used to assign the values which is generated by a function object to a specified number of elements in a range and returns to the one past the last assigned value position. The generator function is defined by the user and it is called successively for assigning the numbers.
Syntax for generate_n() Function in C++
#include <algorithm> template <class OutputIterator, class Size, class Generator> OutputIterator generate_n (OutputIterator first, Size n, Generator gen);
first
Output iterators to the initial positions in a sequence of at least n elements that support being assigned a value of the type returned by gen.
n
Number of values to generate. If negative, the function does nothing. Size shall be (convertible to) an integral type.
gen
Generator function that is called with no arguments and returns some value of a type convertible to those pointed by the iterators. This can either be a function pointer or a function object. Function returns an iterator pointing to the element that follows the last element whose value has been generated.
Complexity
Linear in n: Calls gen and performs an assignment for each element.
Data races
The n first objects at the range pointed by first are modified (each object is modified exactly once).
Exceptions
Throws if any of gen, the element assignments or the operations on iterators throws. Note that invalid arguments cause undefined behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/* The C++ algorithm::generate_n function is used to assign value returned by successive calls of function gen to the first n elements of the sequence pointed by first. */ /* Generate values for sequence with function by algorithm::generate_n function code example */ #include <vector> #include <deque> #include <algorithm> #include <iostream> #include <ostream> using namespace std; int main() { // Assigning random values to vector integer elements vector <int> v1 ( 5 ); vector <int>::iterator Iter1; deque <int> deq1 ( 5 ); deque <int>::iterator d1_Iter; generate_n ( v1.begin ( ), 3 , rand ); cout <<"Vector v1 is ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout <<*Iter1<<" "; cout <<")."<<endl; // Assigning random values to deque integer elements generate_n ( deq1.begin ( ), 4 , rand ); cout <<"Deque deq1 is ( " ; for ( d1_Iter = deq1.begin( ) ; d1_Iter != deq1.end( ) ; d1_Iter++ ) cout <<*d1_Iter<<" "; cout <<")."<<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; }
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; }
Vector Library size() Function in C++
Return size. Returns the number of elements in the vector. This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity. vector::size() is a library function of "vector" header, it is used to get the size of a vector, it returns the total number of elements in the vector. The dynamic array can be created by using a vector in C++. One or more elements can be inserted into or removed from the vector at the run time that increases or decreases the size of the vector. The size or length of the vector can be counted using any loop or the built-in function named size().
Syntax for Vector size() Function in C++
#include <vector> 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
/* get the size of a vector, it returns the total number of elements in the vector by vector::size() library function. */ #include <bits/stdc++.h> using namespace std; int main() { // Initializing a vector of string type vector<string> vec = { "Happy", "8)", "Codings" }; // Clearing the vector // Now size is equal to 0 vec.clear(); // Typecasting vec.size() to int for (int i = 0; i < (int)vec.size() - 1; i++) cout << vec[i] << ' '; cout << "Happy8)Codings"; 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; }
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;
• Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used. • Iterators provide a generic approach to navigate through the elements of a container. Operator (*) : The '*' operator returns the element of the current position pointed by the iterator. Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator points to the next element of the container. Operator (==) and Operator (!=) : Both these operators determine whether the two iterators point to the same position or not. Operator (=) : The '=' operator assigns the iterator. Iterators can be smart pointers which allow to iterate over the complex data structures. A Container provides its iterator type. Therefore, we can say that the iterators have the common interface with different container type. The container classes provide two basic member functions that allow to iterate or move through the elements of a container: begin(): The begin() function returns an iterator pointing to the first element of the container. end(): The end() function returns an iterator pointing to the past-the-last element of the container. Input Iterator: An input iterator is an iterator used to access the elements from the container, but it does not modify the value of a container. Operators used for an input iterator are: Increment operator(++), Equal operator(==), Not equal operator(!=), Dereference operator(*). Output Iterator: An output iterator is an iterator used to modify the value of a container, but it does not read the value from a container. Therefore, we can say that an output iterator is a write-only iterator. Operators used for an output iterator are: Increment operator(++), Assignment operator(=). Forward Iterator: A forward iterator is an iterator used to read and write to a container. It is a multi-pass iterator. Operators used for a Forward iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=). Bidirectional iterator: A bidirectional iterator is an iterator supports all the features of a forward iterator plus it adds one more feature, i.e., decrement operator(--). We can move backward by decrementing an iterator. Operators used for a Bidirectional iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=), Decrement operator(--). Random Access Iterator: A Random Access iterator is an iterator provides random access of an element at an arbitrary location. It has all the features of a bidirectional iterator plus it adds one more feature, i.e., pointer addition and pointer subtraction to provide random access to an element. Following are the disadvantages of an iterator: • If we want to move from one data structure to another at the same time, iterators won't work. • If we want to update the structure which is being iterated, an iterator won?t allow us to do because of the way it stores the position. • If we want to backtrack while processing through a list, the iterator will not work in this case. Following are the advantages of an iterator: • Ease in programming: It is convenient to use iterators rather than using a subscript operator[] to access the elements of a container. If we use subscript operator[] to access the elements, then we need to keep the track of the number of elements added at the runtime, but this would not happen in the case of an iterator. • Code Reusability: A code can be reused if we use iterators. In the above example, if we replace vector with the list, and then the subscript operator[] would not work to access the elements as the list does not support the random access. However, we use iterators to access the elements, then we can also access the list elements. • Dynamic Processing: C++ iterators provide the facility to add or delete the data dynamically.
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; }
Vector Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced. Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as vector::begin.
Syntax for Vector end() Function in C++
#include <vector> iterator end() noexcept; const_iterator end() const noexcept;
This function does not accept any parameter. Function returns an iterator to the element past the end of the sequence. If the vector object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are random access iterator types (pointing to an element and to a const element, respectively). To use vector, include <vector> header. It does not point to the last element, thus to get the last element we can use vector::end()-1.
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* returns the iterator pointing to the past-the-last element of the vector container by vector::end function code example. */ // CPP program to illustrate implementation of begin() function #include <iostream> #include <string> #include <vector> using namespace std; int main() { // declaration of vector container vector<string> myvector{ "This", "is", "HappyCodings" }; // using begin() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0; }
Vector Library Operator Index [] in C++
Access element. Returns a reference to the element at position n in the vector container. A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception. Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.
Syntax for Vector Operator Index [] in C++
#include <vector> reference operator[] (size_type n); const_reference operator[] (size_type n) const;
n
Position of an element in the container. Notice that the first element has a position of 0 (not 1). Member type size_type is an unsigned integral type. Function returns the element at the specified position in the vector. If the vector 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 vector 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 reference returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
If the container size is greater than n, the function never throws exceptions (no-throw guarantee). Otherwise, the behavior is undefined.
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 reference to the element at specified location pos. No bounds checking is performed. Unlike std::map::operator[], this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior. */ /* Access element from a vector by vector::operator[] code example */ #include <iostream> #include <vector> int main () { std::vector<int> myvector (10); // 10 zero-initialized elements std::vector<int>::size_type sz = myvector.size(); // assign some values: for (unsigned i=0; i<sz; i++) myvector[i]=i; // reverse vector using operator[]: for (unsigned i=0; i<sz/2; i++) { int temp; temp = myvector[sz-1-i]; myvector[sz-1-i]=myvector[i]; myvector[i]=temp; } std::cout << "myvector contains:"; for (unsigned i=0; i<sz; i++) std::cout << ' ' << myvector[i]; std::cout << '\n'; 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; }


C++ sample ask to enter a number to reverse it, then check whether reverse is equal to its "original or not", if "it is equal" then it will be palindrome else it will be not be palindrome:
To find the length of the string in 'C++', ask to enter the string and then Find the Length the that string using function "strlen()" of string.h library and display the length value of a string