C++ Learning
C++ Learning
aCharVar = static_cast<char>(anIntVar)
Sample program
#include<iostream>
using namespace std;
int main()
{
bool a=true;
cout<<a<<endl;
cout<<boolalpha<<a;
return 0;
}
To reset the flag use noboolalpha .
Other Flags-
1. hex- use to give output in hexadecimal form.
2. oct- use to give output in octal form.
3. dec- use to give output in decimal form.
4. showbase- it is used to display base of the output result i.e., in case of octal it
shows 0 and in case of hexadecimal numbers it shows 0x. (noshowbase)
5. showpos – it shows positive sign before the positive numbers in output.
(noshowpos)
6. uppercase- it gives output in the form of Uppercase. (nouppercase)
7. setw(n) – it is used to limit the output in n spaces. It needs to be used every time
whenever the width needs to be set.
8. setfill(*) – this will give output of the passed character in the output.
9. left – it makes the output left aligned.
10. right – makes the output right aligned
11. showpoint – it shows the trailing zero in output even if they are not required
double x = 12;
cout<<showpoint<<x;
this will give 12.0000 as output. Only 4 zeros are shown because the default
precision of floating-point variable is 6 digits. (noshowpoint)
12. setprecision(n) – it sets the precision of output to desired value given to n.
Floating Point (Default Printing Format)
1. No trailing zero.
double x= 1.2300;
cout<<x<<endl;
This will give output as 1.23. No trailing zeros
2. Precision means total digits (excluding the digits after e)
double x = 1567.56732;
cout<<x<<endl;
This will give 1567.57 as output. The initialised value is rounded of to 6 digits.
3. Default precision value is 6.
4. When value before decimal point does not fit in 6 digits, power format is used.
i.e., 1234568.3 is printed as 1.23457e+06. This is known as Power Format.
2. Scientific Format
o Here the precision after the decimal point is set to 6.
i.e., double x= 1.23;
cout<<scientific<<x;
It will show output as 1.230000e+00
o double y = 1122456.453;
cout<<scientific<<y;
It will show output as 1.122456e+06
Printing Hello World without using semicolon
#include<iostream>
using namespace std;
int main()
{
if(cout<<"Hello World")
{
}
return 0;
}
wchar_t
1. it is similar to char type, except that wide char take up twice the space and
can take much larger values as result
2. Type for wide char is wchar_t
3. It occupies 4 bytes of space
4. include <iostream>
5. using namespace std;
6.
7. int main()
8. {
9. wchar_t w = L'A';
10. cout << "Wide character value:: " << w <<
endl ;
11. cout << "Size of the wide char is:: " <<
sizeof(w);
12. return 0;
13. }
4. L is the prefix for wide character literals and wide character strings literals
which tells compiler that the char or string is of type wide-char.
* Dereference
3 *, / , % Multiplication/division/modulus left-to-right
12 || Logical OR left-to-right
14 = Assignment right-to-left
+= , -= Addition/subtraction assignment
*= , /= Multiplication/division assignment
default:
and so on…..
Conditional operator
Min= (alpha<beta) ? alpha : beta
This is used to assess the given condition and assign the result accordingly
STRUCTURES
Structure is collection of simple variables which can be integers, float and characters.
Data items in a structure is called as members
Defining a structure
Struct part
{
int modelnumber;
Int partnumber;
Float cost;
};
int main()
{
part part1;
}
The structure definition serves only as a blueprint for the creation of variables of type
part. It does not itself create any structure variables; that is, it does not set aside any space in
memory or even name any variables. This is unlike the definition of a simple variable, which
does set aside memory
A structure within a structure can be formed. Infinite number of structure can be incorporated
within a given structure.
Int main()
{
Struct Distance
{
int feet;
float inches;
};
Struct Room
{
Distance length;
Distance breadth;
};
Structure should be declared before the main program and while nesting two structures the
inner structure should be declared first.
FUNCTIONS
1. Basic Information
void starline();
Void indicates that the return type of function which is null. This function will not return any
value
Empty brackets indicate that this function will have no arguments.
The function should be declared before it is called in any part of the program.
The declaration tells the compiler that at some point in time this function will come up.
Starline();
void starline()
{
for(int n=0; n<=45; n++)
cout<<”*”;
cout<<endl;
}
Above statements are called as function definition. The definition contains the actual code for the
function.
Function definition is not terminated by semicolon.
2. Passing Arguments to a Function
void engldisp(Distance)
Here Distance which is a structure is passed as an argument
When values are passed as an argument then the function creates a copy of it.
For e.g.
Void engldisp(Distance dd)
{
cout << dd.feet << “\’-” << dd.inches << “\””;
}
When this function is called from main with an argument of structure type then that structure
Will be copied to structure dd.
3. Returning values from a function
float lbstokg(float)
Here the function will return a float value.
float lbstokg(float pounds)
{
float kilograms = 0.453592 * pounds;
return kilograms;
Following line denotes a function declaration which will return a structure type value
Distance addengl(Distance, Distance);
Reference arguments
A reference provides an alias—a different name—for a variable. One of the most important
uses for references is in passing arguments to functions
Passing arguments by reference uses a different mechanism. Instead of a value being passed
to the function, a reference to the original variable, in the calling program, is passed. (It’s
actually the memory address of the variable that is passed, although you don’t need to know
this.) An important advantage of passing by reference is that the function can access the
actual variables in the calling program. Among other benefits, this provides a mechanism for
passing more than one value from the function back to the calling program
For e.g.
In the above example the changes made in intp and fracp will directly reflect in intpart and
fracpart
In the declaration float& defines the type of argument and & denotes its address in the
memory
In the definition an alias name is created i.e. intp and fracp which follow the float&
Functions with the same name but different number and types of arguments can be used and
the function will still work properly
Above examples shows that how function with same name but different arguments can be
used
5. Recursion
Recursion occurs when a function calls itself
Take a look at this example of finding out factorial of a given number.
#include <iostream>
using namespace std;
unsigned long factfunc(unsigned long);
int main()
{
int n;
unsigned long fact;
cout << “Enter an integer: “;
cin >> n;
fact = factfunc(n);
cout << “Factorial of “ << n << “ is “ << fact << endl;
return 0;
}
In the above example in function definition the function calls itself. This recursion will occurs
until the value of n becomes 1.
6. Inline function
We mentioned that functions save memory space because all the calls to the function cause
the same code to be executed; the function body need not be duplicated in memory. When
the compiler sees a function call, it normally generates a jump to the function. At the end of
the function it jumps back to the instruction following the call,
While this sequence of events may save memory space, it takes some extra time. There must
be an instruction for the jump to the function (actually the assembly-language instruction
CALL or something similar), instructions for saving registers, instructions for pushing
arguments onto the stack in the calling program and removing them from the stack in the
function (if there are arguments), instructions for restoring registers, and an instruction to
return to the calling program. The return value (if any) must also be dealt with. All these
instructions slow down the program.
To save execution time in short functions, you may elect to put the code in the function body
directly inline with the code in the calling program. That is, each time there’s a function call
in the source file, the actual code from the function is inserted, instead of a jump to the
function.
Long sections of repeated code are generally better off as normal functions: The savings in
memory space is worth the comparatively small sacrifice in execution speed. But making a
short section of code into an ordinary function may result in little savings in memory space,
while imposing just as much time penalty as a larger function. In fact, if a function is very
short, the instructions necessary to call it may take up as much space as the instructions within
the function body, so that there is not only a time penalty but a space penalty as well.
In such cases you could simply repeat the necessary code in your program, inserting the same
group of statements wherever it was needed. The trouble with repeatedly inserting the same
code is that you lose the benefits of program organization and clarity that come with using
functions. The program may run faster and take less space, but the listing is longer and more
complex.
The solution to this quandary is the inline function. This kind of function is written like a
normal function in the source file but compiles into inline code instead of into a function. The
source file remains well organized and easy to read, since the function is shown as a separate
entity. However, when the program is compiled, the function body is actually inserted into the
program wherever a function call occurs.
7. Default arguments
While declaring, functions can be provided with default arguments so that in case if we miss
trailing argument, it will be replaced by default argument
Two different kinds of scope are important here: local and file. (We’ll see another one, class
scope, later.)
• Variables with local scope are visible only within a block.
• Variables with file scope are visible throughout a file.
A block is basically the code between an opening brace and a closing brace. Thus, a function
body is a block.
There are two storage classes: automatic and static.
• Variables with storage class automatic exist during the lifetime of the function in which
they’re defined.
• Variables with storage class static exist for the lifetime of the program.
Local Variable
So far almost all the variables we’ve used in example programs have been defined inside the
function in which they are used. That is, the definition occurs inside the braces that delimit
the function body:
void somefunc()
{
int somevar;
float othervar;
}
Here somevar and othervar are local variable. They exist within the somefunc() and cannot be
accessed by any other function. They are in existence as long as somefunc() is operating. As
soon as control is passed from somefunc() into another function the value of somevar and
othervar are destroyed. This type of variables has automatic storage class. It means the
variable are automatically created when function is called and gets destroyed when control is
passed to other function.
9. Global Variable
The next kind of variable is global. While local variables are defined within functions, global
variables are defined outside of any function. (They’re also defined outside of any class, as
we’ll see later.) A global variable is visible to all the functions in a file (and potentially in
other files). More precisely, it is visible to all those functions that follow the variable’s
definition in the listing. Usually, you want global variables to be visible to all functions, so
you put their declarations at the beginning of the listing. Global variables are also sometimes
called external variables, since they are defined external to any function.
#include <iostream>
using namespace std;
#include <conio.h>
char ch = ‘a’; Global variable declaration
void getachar();
void putachar();
As we noted, global variables are visible in the file in which they are defined, starting at the
point where they are defined. If ch were defined following main () but before getachar(), it
would be visible in getachar() and putachar(), but not in main().
Static local variables are useful only when we want to retain the value of variable defined
within a function
Static local variables are used when it’s necessary for a function to remember a value when it
is not being executed; that is, between calls to the function. In the next example, a function,
getavg(), calculates a running average. It remembers the total of the numbers it has averaged
before, and how many there were. Each time it receives a new number, sent as an argument
from the calling program, it adds this number to the total, adds 1 to a count, and returns the
new average by dividing the total by the count.
#include <iostream>
using namespace std;
float getavg(float);
int main()
{
float data=1, avg;
while(data != 0 )
{
cout << “Enter a number: “;
cin >> data;
avg = getavg(data);
cout << “New average is “ << avg << endl;
}
return 0;
}
#include <iostream>
using namespace std;
class smallobj //define a class
{
private:
int somedata;
public:
void setdata(int d)
{ somedata = d; }
void showdata()
{ cout << “Data is “ << somedata << endl; }
};
int main()
{
smallobj s1, s2;
s1.setdata(1066);
s2.setdata(1776);
s1.showdata();
s2.showdata();
return 0;
};
In the above program there are one data item and two-member function. Usually, the data
items are private and can be accessed only by member function. This is done to prevent data
item to be modified by other functions.
Body of class is delimited by braces and terminated by a semicolon
Member function is defined like any other normal function i.e. in the beginning they mention
return type followed by function name and arguments if any.
e.g. void setdata(int d)
Member function defined inside a class doesn’t set aside memory space as long as any object
of the class is created.
Member function are created as inline function by default
Objects are created by mentioning class name followed by object name
e.g., smallobj s1,s2;
While calling member function object names must be used along with function name
E.g., s1.setdata();
Here object s1 calls the member function setdata() using dot operator. This is because the
member function always acts on a specific object
3. CONSTRUCTORS
Data items inside a class can be initialised by using a member function or by using
Constructors.
Sometimes it is very convenient if data items are initialised automatically when they are
created without requiring member function.
This is done by a special function called Constructors.
COUNTER EXAMPLE
In this example we want the count initially be set to zero. For that we will use a constructor.
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Counter
{
private:
unsigned int count;
public:
Counter() : count(0)
{ }
void inc_count()
{ count++; }
int get_count()
{ return count; }
};
////////////////////////////////////////////////////////////////
int main()
{
Counter c1, c2;
cout << “\nc1=” << c1.get_count();
cout << “\nc2=” << c2.get_count();
c1.inc_count();
c2.inc_count();
c2.inc_count();
cout << “\nc1=” << c1.get_count();
cout << “\nc2=” << c2.get_count();
cout << endl;
return 0;
}
The initialization takes place following the member function declarator but before the
function body. It’s preceded by a colon. The value is placed in parentheses following the
member data
#include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist()
{
cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist()
{ cout << feet << “\’-” << inches << ‘\”’; }
void add_dist(Distance, Distance );
};
//--------------------------------------------------------------
//add lengths d2 and d3
void Distance::add_dist(Distance d2, Distance d3)
{
inches = d2.inches + d3.inches;
feet = 0;
if(inches >= 12.0)
{
inches -= 12.0;
feet++;
}
feet += d2.feet + d3.feet;
}
////////////////////////////////////////////////////////////////
int main()
{
Distance dist1, dist3;
Distance dist2(11, 6.25);
dist1.getdist();
dist3.add_dist(dist1, dist2);
cout << “\ndist1 = “; dist1.showdist();
cout << “\ndist2 = “; dist2.showdist();
cout << “\ndist3 = “; dist3.showdist();
cout << endl;
return 0;
}
In the above program 2 objects has been passed directly to the member function as arguments
e.g., dist3.add_dist(dist1, dist2);
one more thing to observe is that the member function can be defined outside the class
as shown above;
void Distance::add_dist(Distance d2, Distance d3)
above declaration of function consists of class name i.e. Distance in order to identify to which
to which class the function is associated. It is preceded by return type of the function and
followed by double colon which is know as scope resolution operator.
dist3.add_dist(dist1, dist2)
This function allows the function to access the data items of the objects provided as
arguments. Changes are directly made in the data items of the object which called the
function i.e., in this case dist3
Private is default in classes, therefore this word is unnecessary. The classes can be defined
without using this keyword private.
struct foo
{
void func();
private:
int data1;
};
Structures can also be used like classes. The only difference is that the public is default in
structures. But it is better to use classes instead of sturctures.
6. CLASSES OBJECTS AND MEMORY
Each object has its own separate data items but all the objects in a given class uses the
same function. The member function are created and placed in the memory only once.\
#include <iostream>
using namespace std;
class foo
{
private:
static int count;
public:
foo()
{ count++; }
int getcount()
{ return count; }
};
int foo::count = 0;
int main()
{
foo f1, f2, f3; //create three objects
cout << “count is “ << f1.getcount() << endl;
cout << “count is “ << f2.getcount() << endl;
cout << “count is “ << f3.getcount() << endl;
return 0;
Take a look at above program in which the count is defined as a static type integer. Now this
integer is shared by all objects created in the main function because the static type of
variables is only created once.
Why is this two-part approach used? If static member data were defined inside the class (as it
actually, was in early versions of C++), it would violate the idea that a class definition is only
a blueprint and does not set aside any memory. Putting the definition of static member data
outside the class also serves to emphasize that the memory space for such data is allocated
only once, before the program starts to execute, and that one static member variable is
accessed by an entire class; each object does not have its own version of the variable, as it
would with ordinary member data. In this way a static member variable is more like a global
variable.
Member function within a class can be made constant so that they should not modify any of it
class’s member data.
If a object is defined as constant then a constant function can only access it.
1) ARRAY FUNDAMENTALS
#include <iostream>
using namespace std;
int main ()
{
int age [4];
for (int j=0; j<4; j++)
{
cout << “Enter an age: “;
cin >> age[j];
}
for (j=0; j<4; j++) //display 4 ages
cout << “You entered “<< age[j] << endl;
return 0;
}
Consider the above example the array is of int type. While initialising the array its size is
mentioned within the brackets. Its members are accessed by using an index in the form of
j. For e.g., first element will be age[0], second element will be age[1]…and so on.
Notice that the first array element is numbered 0
2) ARRAY INITIALISATION
Arrays can be initialised as follows:
3) MULTIDIMENSIONAL ARRAY
You can think about sales as a two-dimensional array, laid out like a checkerboard. Another
way to think about it is that sales is an array of arrays. It is an array of DISTRICTS elements,
each of which is an array of MONTHS elements.
4) FORMATTING NUMBERS
setiosflags(ios::fixed) – This code prevents the number form getting printed in exponential format.
i.e., 3.45e3
setiosflag(ios::showpoint)- This code makes sure that decimal point is always printed.
i.e., 123.00 instead of 123
setprecision(2)- This code decides the number of integer that will appear after the decimal point.
#include <iostream>
#include <iomanip> //for setprecision, etc.
using namespace std;
const int DISTRICTS = 4; //array dimensions
const int MONTHS = 3;
void display(double[DISTRICTS][MONTHS] );
When array is passed as an argument, its type and dimensions are written. In the above
example the array is of type double and its dimensions are expressed by DISTRICTS and
MONTHS.
It is not necessary to declare array before passing it as an argument in function declaration.
Array can be later on declared and defined in main program. Unlike structures which are
needed to declare before passing it as an argument
int main()
{
twodimension(arr);
}
Here the 2D array is directly passed as we are using a pointer to pointer in function.
int main()
{
Here the array is type casted before passing it to the function i.e., twodimension((int *) arr)
b) void twodimension((int *)arr, m, n )
{
for(int j=0;j<n;j++)
{
for(int i=0; i<m; i++)
{
cout<<arr[i][j]<<endl;
}
int main()
{
twodimension( arr);
}
Here the array is type casted after it has been passed to the function i.e., void
twodimension( (int*) arr),m , n)
6) ARRAY OF STRUCTURES
#include <iostream>
using namespace std;
const int SIZE = 4;
struct part
{
int modelnumber;
int partnumber;
float cost;
};
int main()
{
int n;
part apart[SIZE];
for(n=0; n<SIZE; n++)
{
cout << endl;
cout << “Enter model number: “;
cin >> apart[n].modelnumber;
cout << “Enter part number: “;
cin >> apart[n].partnumber;
cout << “Enter cost: “;
cin >> apart[n].cost; //get cost
}
cout << endl;
for(n=0; n<SIZE; n++)
{
cout << “Model “ << apart[n].modelnumber;
cout << “ Part “ << apart[n].partnumber;
cout << “ Cost “ << apart[n].cost << endl;
}
return 0;
}
The array of structures is defined in the statement
part apart[SIZE];
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Stack
{
private:
enum {MAX = 10};
int st[MAX];
int top;
public:
Stack()
{ top = 0; }
void push(int var)
{ st[++top] = var; }
int pop()
{ return st[top--]; }
};
int main()
{
Stack s1;
s1.push(11);
s1.push(22);
cout << “1: “ << s1.pop() << endl; //22
cout << “2: “ << s1.pop() << endl; //11
s1.push(33);
s1.push(44);
s1.push(55);
s1.push(66);
cout << “3: “ << s1.pop() << endl; //66
cout << “4: “ << s1.pop() << endl; //55
cout << “5: “ << s1.pop() << endl; //44
cout << “6: “ << s1.pop() << endl; //33
return 0;
}
int st[MAX];
But the array can also be defined in the main program also.
This definition of MAX is unusual. In keeping with the philosophy of encapsulation, it’s
preferable to define constants that will be used entirely within a class, as MAX is here, within
the class. Thus the use of global const variables for this purpose is nonoptimal. Standard C++
mandates that we should be able to declare MAX within the class as
static const int MAX = 10;
This means that MAX is constant and applies to all objects in the class. Unfortunately, some
compilers, including the current version of Microsoft Visual C++, do not allow this newly
approved construction.
srand(time(NULL));
rand()
rand ()
The rand() function is used in C/C++ to generate random numbers in the range [0,
RAND_MAX).
Note: If random numbers are generated with rand() without first calling srand(), your
program will create the same sequence of numbers each time it runs.
srand()
The srand() function sets the starting point for producing a series of pseudo-random
integers. If srand() is not called, the rand() seed is set as if srand(1) were called at program
start. Any other value for seed sets the generator to a different starting point .
Note: The pseudo-random number generator should only be seeded once, before any calls
to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every
time you wish to generate a new batch of pseudo-random numbers.
Standard practice is to use the result of a call to srand(timse(0)) as the seed. However,
time() returns a time_t value which vary everytime and hence the pseudo-random number
vary for every program call.
9) STRINGS
There are two types:
1) C-strings – These are array of type char
2) Strings that are object string class.
a) C- String variables
#include <iostream>
using namespace std;
int main()
{
const int MAX = 80;
char str[MAX];
cout << “Enter a string: “;
cin >> str;
cout << “You entered: “ << str << endl;
return 0;
}
Here string is defined as an array of type char. Above program is not able to read spaces and
print the character which are continuous. For e.g., if we enter my name is …..then only “my”
will be printed.
b) String Constants.
Here the string constant is written as a normal English phrase, delimited by quotes.
The normal input operation i.e., cin>>str is not able to read the spaces embedded in
the strings. So in order to read the spaces between the strings we need to use the
function
cin.get(str, MAX)
wher str is array of type char and MAX is the number of elements it can hold
Now the above program will be able to read the spaces between the words but it will
not be able to read multiple lines. For that we need to modify cin.get()
Here the dollar sign indicates the character to be entered to end the process.
Any character can be used
#inlcude<cstring> - This file must be included to use the function such as strcpy() which is
used to copy strings.
strcpy(str2, str1) – This function is used to copy one string into another.
11) ARRAY OF STRINGS
Sounds weird, but array of strings exists. By the definition of strings which are defined as
array of type char. Array of strings can be defined as follows-
#include <iostream>
using namespace std;
int main()
{
const int DAYS = 7;
const int MAX = 10;
char star[DAYS][MAX] = { “Sunday”, “Monday”, “Tuesday”,
“Wednesday”, “Thursday”,
“Friday”, “Saturday”};
for(int j=0; j<DAYS; j++)
cout << star[j] << endl;
return 0;
}
In the above program star is defined as array of strings. The DAYS defines the number of
different string elements and MAX defines the number of character in each string i.e., limit of
the string.
In this case we don’t need a second index to access the elements of the array
For e.g., the elements of star can be accessed by inserting star[j]
#include <iostream>
#include <cstring> //for strcpy()
using namespace std;
class part
{
private:
char partname[30];
int partnumber;
double cost;
public:
void setpart(char pname[], int pn, double c)
{
strcpy(partname, pname);
partnumber = pn;
cost = c;
}
void showpart()
{
cout << “\nName=” << partname;
cout << “, number=” << partnumber;
cout << “, cost=$” << cost;
}
};
int main()
{
part part1, part2;
part1.setpart(“handle bolt”, 4473, 217.55);
part2.setpart(“start lever”, 9924, 419.25);
cout << “\nFirst part: “; part1.showpart();
cout << “\nSecond part: “; part2.showpart();
cout << endl;
return 0;
}
By using concat() function we can add two C-type strings together. The result of the this
operation is kept in the first string that is passed as an argument
1) strcmp(str1,str2)
This function compares two C-type strings and returns 0 if strings are same otherwise it
returns 1 or -1 depending upon the first mismatch character in str1 and str2.
If first mismatch character of str1 is having ASCII value greater than the character of str2
then value 1 is returned otherwise -1 is returned.
The x will be 0 if the strings are equal and 1 or -1 depending upon the ASCII value of
mismatch characters.
3) strcasecmp(str1, str2)
This function is used to compare strings regardless of the case i.e., uppercase or
lowercase
char ch[] = “HELLO”;
char ch1[] = “hello”;
It is similar to above function. The only difference is that it allows the user to compare a
specific number of characters regardless of the case of the letters.
7) strstr(str1, str2)
This function is used to find a string within another string. It returns a pointer indicating
the starting position of the string to be found.
8) strrev(str)
This function reverses the string provided as an argument.
9) strlwr(str)
It convers all the characters in the string to a lower case.
10) strupr(str)
It converts all the characters in the string to uppercase.
11) strdup(str)
This is used to duplicate a string. It returns a pointer of type char.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1(“Man”);
string s2 = “Beast”;
string s3;
s3 = s1;
cout << “s3 = “ << s3 << endl;
s3 = “Neither “ + s1 + “ nor “;
s3 += s2;
cout << “s3 = “ << s3 << endl;
s1.swap(s2);
cout << s1 << “ nor “ << s2 << endl;
return 0;
}
4) Unlike C-type string, C++ string is improved and easy to use. We do not need to define the
limits
For e.g., we define C-type strings as char name[30]. Here we provide the limit of the string
whereas in standard C++ string we define strings as
string name;
we need not to define its limits. It is all managed by the compiler.
5) In C++ standard strings we can assign one string to another with an assignment operator
directly
string s1(“Man”);
string s2 = “Beast”;
getline(cin, fullname)
getline(cin, fullname, ‘$’)
s1+=s2;
string s1= “ In Xanadu did Kubla Kahn a stately pleasure dome decree”;
int n;
n=s1.find(“Kubla”);
this will give the position of the required word in above string
n=s1.find_first_of(“spde”);
This will give the position of whichever comes first from spde.
n=s1.find_first_not_of(“aeiouAEIOU”);
9) s1.replace(9,5,s2)
where 9 is the starting position of the letter and 5 is its length
This will replace Count with Lord
12) s1.erase(s1.size()-1,1)
since last character in a string is automatically inserted as ‘\0’ therefore we need to subtract -1
from total size to get the last character
15) aName.substr(0,2)
This will give out the first two characters of string named aName
16) word.at[j]
This will give the character present in string word at j position
18) Str.c_str()
This function is very useful in converting a string to an array. This function returns a pointer
to the given string that is converted into array of char type. But remember it is a constant
function.
19) Str.substr(x,y)
This is use to extract substring from a string. Here x denotes the starting point and y denotes
the number of characters to be extracted.
20) Strcmp(str1,str2)
This function is used to compare two strings. It returns 0 if the strings are equal and -1 if they
are not.
10) Operator Overloading
The rather forbidding term operator overloading refers to giving the normal C++ operators,
such as +, *, <=, and +=, additional meanings when they are applied to user-defined data
types.
Normally
a = b + c;
works only with basic types such as int and float, and attempting to apply it when a, b, and c
are objects of a user-defined class will cause complaints from the compiler. However, using
overloading, you can make this statement legal even when a, b, and c are user-defined types .
class Counter
{
private:
unsigned int count;
public:
Counter() : count(0)
{}
unsigned int get_count()
{ return count; }
void operator ++ ()
{
++count;
}
};
int main()
{
Counter c1, c2;
c1=++c2;
Then we need to change the return type of the operator from void
Counter temp;
temp.count=++count;
return temp;
Instead of creating an object of Counter class we can directly return value in this way
Here we have included int inside the bracket. It works as an argument to the operator.
#include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
Distance (): feet (0), inches (0.0)
Distance (int ft, float in): feet(ft), inches(in)
{}
void getdist()
{
cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist() const
{ cout << feet << “\’-” << inches << ‘\”’; }
Distance operator + ( Distance ) const;
};
Distance Distance::operator + (Distance d2) const //return sum
{
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if(i >= 12.0) //if total exceeds 12.0,
{
i -= 12.0; //by 12.0 and
f++;
}
return Distance(f,i);
}
int main()
{
Distance dist1, dist3, dist4;
dist1.getdist();
Distance dist2(11, 6.25);
dist3 = dist1 + dist2;
dist4 = dist1 + dist2 + dist3;
cout << “dist1 = “; dist1.showdist(); cout << endl;
cout << “dist2 = “; dist2.showdist(); cout << endl;
cout << “dist3 = “; dist3.showdist(); cout << endl;
cout << “dist4 = “; dist4.showdist(); cout << endl;
return 0;
}
Here return type is a Distance which is a class. This operator takes another class as argument.
The object on the left side of the operator is the object of which the operator is a member. The
object on the right side of the operator is furnished as argument.
return Distance(f , i)
It creates a nameless object of class Distance and two arguments are passed to it due to which
the constructor which is defined to handle two arguments is called. This nameless object is
then returned.
#include <iostream>
using namespace std;
#include <process.h> //for exit ()
const int LIMIT = 100; //array size
////////////////////////////////////////////////////////////////
class safearay
{
private:
int arr[LIMIT];
public:
int& operator [](int n)
{
if( n< 0 || n>=LIMIT )
{ cout << “\nIndex out of bounds”; exit(1); }
return arr[n];
}
};
int main()
{
safearay sa1;
for(int j=0; j<LIMIT; j++)
sa1[j] = j*10;
for(j=0; j<LIMIT; j++)
{
int temp = sa1[j];
cout << “Element “ << j << “ is “ << temp << endl;
}
return 0;
}
11) Inheritance
#include <iostream>
using namespace std;
int main()
{
CountDn c1;
cout << “\nc1=” << c1.get_count();
++c1; ++c1; ++c1;
cout << “\nc1=” << c1.get_count();
--c1; --c1; //decrement c1, twice
cout << “\nc1=” << c1.get_count();
cout << endl;
return 0;
}
Objects of the derived class can use the function from the base class.
// staken.cpp
// overloading functions in base and derived classes
#include <iostream>
using namespace std;
#include <process.h>
class Stack
{
protected:
enum { MAX = 3 };
int st[MAX];
int top;
public:
Stack()
{ top = -1; }
void push(int var)
{ st[++top] = var; }
int pop()
{ return st[top--]; }
};
class Stack2 :
{
public:
void push(int var)
{
if(top >= MAX-1)
{ cout << “\nError: stack is full”; exit(1); }
Stack::push(var);
}
int pop() //take number off stack
{
if(top < 0) //error if stack empty
{ cout << “\nError: stack is empty\n”; exit(1); }
return Stack::pop();
}
}
int main()
{
Stack2 s1;
s1.push(11); //push some values onto stack
s1.push(22);
s1.push(33);
cout << endl << s1.pop();
cout << endl << s1.pop();
cout << endl << s1.pop();
cout << endl << s1.pop();
cout << endl;
return 0;
}
1) begin()
This function returns an iterator pointing to the first element in the vector
2) end()
This function returns an iterator pointing to the theoretical element that follows the last
element in the vector.
4) rend()
Returns a reverse iterator pointing to theoretical element preceding the first element in the
vector.
5) crbegin()
Returns a constant reverse iterator pointing to the last element in the vector (reverse
beginning). It moves form last to first element
6) crend()
Returns a constant reverse iterator pointing to the theoretical element preceding the first
element in the vector (considered as reverse end)
7) size()
Returns the number of elements in the vector
8) capacity()
Returns the size of the storage space currently allocated to the vector expressed as number
of elements
9) resize()
Resizes the container so that it contains ‘n’ elements.
vectorname.resize(int n)
10) empty()
Returns whether the container is empty. The return type is bool.
11) shrink_to_fit()
Reduces the capacity of the container to fit its size and destroys all elements beyond the
capacity.
12) reserve()
Requests that the vector capacity be at least enough to contain n elements
13) at(g)
Returns a reference to the element at position ‘g’ in the vector
vectorname.at(position)
14) front()
Returns a reference to the first element in the vector.
vectorname.front()
15) back()
Returns a reference to the last element in the vector.
vectorname.back()
16) assign()
This function is used to assign new values to the elements in the vector replacing the old
one.
vectorname.assign(int size, int value)
size-number of values to be assigned
value- value to be assigned
vectorname.assign(array, arr+size)
17) push_back()
This function is used to push elements into a vector from the back. The new value is
inserted into the vector at the end, after the current last element and the container size is
increased by 1
vectorname.push_back(value)
The value to be added in the back is passed as the parameter.
myvector = {1,2,3,4,5}
myvector.push_back(6);
Output = {1,2,3,4,5,6}
18) pop_back()
This function is used to pop or remove elements from a vector from the back
vectorname.pop_back()
19) insert()
This function is used to insert elements in the vector at a desired location.
vectorname.insert(position, val)
position – it specifies the iterator which points to the position where the insertion is to be
done.
val- it specifies the value to be inserted.
20) erase()
This function is used to remove elements from a specified position or range.
vectorname.erase(position)
vectorname.erase(starting position, ending position)
21) clear()
This function is used to remove all the elements in a vector thus making it of size 0.
22) Swap()
This function is used to swap elements of one vector with another irrespective of their
sizes.
vectorname.swap(vector)
23) emplace()
This function extends the container by inserting a new element at the position.
Reallocation happens only if there is a need for more space. Here the container size
increases by one.
position- it specifies the iterator pointing to the position in the container where the new
element is to be inserted.
Return value- this function returns an iterator that points to the newly inserted element.
1) all_of()
Test condition for all elements in range.
It checks for a given property on every element and returns true when each element in the
range satisfies specified property, else return false.
https://www.geeksforgeeks.org/stdall_of-in-cpp/
2) any_of()
This function checks for a given range if there is even one element satisfying a given
property mentioned in function. Return true if at least one element satisfies the property
else returns false.
https://www.geeksforgeeks.org/useful-array-algorithms-in-c-stl/
3) none_of()
This function returns true if none of the elements satisfies the given condition else return
false.
https://www.geeksforgeeks.org/useful-array-algorithms-in-c-stl/
Return value:
It returns a bool type value.
none_of(InputIterator first, InputIterator last, UnaryPredicate pred);
4) for_each()
This function helps in making changes in each element without using for loop or while
loop.
for_each(InputIterator first, InputIterator last, Function fnc);
first-The beginning position from where the function operations have to be executed.
last- The ending position till where function has to be executed.
fnc/obj- The third argument is a function or an object function which operation would be
applied to each element.
https://www.geeksforgeeks.org/for_each-loop-c/
5) find()
Finds the element in the given range of numbers. Returns an iterator to the first element in
the range that compares equal to val. If no such element is found, the function returns last.
first-starting point
last- ending point
value- value to be searched.
https://www.geeksforgeeks.org/std-find-in-cpp/
Return value:
Returns an iterator to the first element in the range that compares equal to val.
If no elements match, the function returns last.
6) find_if()
Returns an iterator to first element in the range for which pred (Unary function) returns
true. If no such element is found, the function returns last.
https://www.geeksforgeeks.org/stdfind_if-stdfind_if_not-in-c/
7) find_if_not()
Returns an iterator to first element in the range for which pred( Unary function) returns
false. If no such element is found, the function returns last.
https://www.geeksforgeeks.org/stdfind_if-stdfind_if_not-in-c/
8) find_end()
This function is used to find the last occurrence of sub-sequence inside a container. It
searches the range[first1, last1] for the last occurrence of the sequence defined by [first2,
last2], and returns an iterator to first element, or last if no occurrence are found.
9) find_first_of()
This function is used to compare elements between two containers. It compares all the
elements in a range [first1, last1] with the elements in the range [first2, last2] and if any
of the elements present in the second range is found in the first one, then it returns an
iterator to that element.
If there are more than one common element in both the ranges then an iterator to the first
common element present in the first container is returned. In case there is no match, the
iterator pointing to last1 is returned.
https://www.geeksforgeeks.org/stdfind_first_of-in-cpp/
Return value- it returns an iterator to the first element in [first1, last1] that is part of
[first2, last2]. If no matches are found of [first2,last2] is empty the function returns last1.
10) adjacent_find()
https://www.geeksforgeeks.org/stdadjacent_find-in-c/
Return value:
An iterator to the first of the first pair of identical elements that is, the first iterator it such
that *it=*(it+1) for the first version or p (*it, *(it+1))! =false for the second version
If no such elements are found false is returned.
11) count()
Returns the number of occurrences of an element in a given range. Returns the number of
elements in the range [first, last] that compare equal to val.
first,last= input iterators to the initial and final position of the sequence of elements,
val- Value to match.
https://www.geeksforgeeks.org/std-count-cpp-stl/
12) count_if()
this function returns the numbers of elements that satisfies the given condition
int n= count_if(Itertor first, Iterator last, Unary Predicate p);
first, last- input iterator to the initial and final position of the sequence of elements
p= condition to be satisfied by the number.
https://www.geeksforgeeks.org/count_if-in-c/
13) mismatch ()
This function returns the 1st mismatch pair pointer, first element pointing to position first
mismatch element of first container, second element pointing to position of first mismatch
element of 2nd container. If no mismatch is found, 1st element points to position after last
element of 1st container and 2nd points to corresponding position of 2nd pointer.
https://www.geeksforgeeks.org/stdmismatch-examples-c/
14) equal()
It helps to compare the elements within the range [first1, last1] with those within range
beginning at first2.
bool equal ( InputIterator first1, InputIterator last1, InputIterator first2)
https://www.geeksforgeeks.org/stdequal-in-cpp/
first1, last1- initial and final position of the first sequence. All the elements are present
within the range [first1, last1]
first2 – Initial position of the second sequence.
Return value:
Returns true if all the elements in both range match; otherwise, false.
bool equal ( InputIterator first1, InputIterator last1, InputIterator first2,
BinaryPredicate pred);
first1, last1- initial and final position of the first sequence. All the elements are present
within the range [first1, last1]
first2 – Initial position of the second sequence.
Pred – binary function that accepts two elements as arguments and returns a value
convertible to Boolean.
Return value:
Returns true if all the elements in both range match; otherwise, false.
15) is_permutation()
https://www.geeksforgeeks.org/stdis_permutation-c-stl/
first1, last1- initial and final position of the first sequence. All the elements are present
within the range [first1, last1]
Return value:
Returns true if all the elements in both range match; otherwise, false.
16) search()
This function is used to find out the presence of a subsequence satisfying a condition with
respect to another sequence.
It searches the secquence [first1, last1) for the first occurrence of the subsequence
defined by [first2, last2] and returns an iterator to its first element of the
occurrence, or last1 if no occurrences are found.
It compares the elements in both the ranges sequentially using operator == or
based on any given predicate. A subsequence of [first, last1) is considered a
match only when this is true for all the elements of [first2, last2]. Finally
std::search returns the first such occurrence.
first1- Forward iterator to the beginning of the subsequence of first container to be searched into.
last1 Forward iterator to the ending of the subsequence of first container to be searched into
first2 -Forward iterator to the beginning of the subsequence of second container to be searched for.
last2- Forward iterator to the ending of the subsequence of second container to be searched for.
Return- an iterator to the first element of the first occurrence of [first2, last2) in [first1,last1) or last1
if no occurrence are found.
pred – binary function that accepts two elements as arguments (one from each of the two container, in
the same order) and returns a value convertible to bool. The returned value indicates whether the
elements are considered to match in the context of the function
17) search_n()
This function is used to determine whether a given element satisfies a predicate a given
no. of times consecutively within the container elements.
It searches the range [first, last) for sequence of count elements, each comparing equal to
given value (version 1) or satisfying a predicate (version 2)
The function returns an iterator to the first such element, or an iterator to the last element
of the container, if no such sequence is found.
https://www.geeksforgeeks.org/stdsearch_n-with-example-in-cpp/
2) For comparing elements using a predicate.
Pred- Binary function accepts two arguments (one element from the sequence as first,
and val as second), and returns a value convertible to bool. The value returned indicates
whether the element is considered a match in the context of this function.
https://www.geeksforgeeks.org/stdsearch_n-with-example-in-cpp/
1) copy()
strt_iter1 – The pointer to the beginning of the source container, from where elements have
to be started copying
end_iter1, - The pointer to the end of the source container, from where elements have to be
copied.
strt_iter2- The pointer to the beginning of the destination container, to where elements have
to be started copying.
https://www.geeksforgeeks.org/different-methods-copy-c-stl-stdcopy-copy_n-copy_if-
copy_backward/
num- Integer specifying how many numbers would be copied to destination container
starting from strt_iter1. If a negative number is entered, no operation is performed