Initial commit
This commit is contained in:
@@ -0,0 +1,266 @@
|
||||
A C++ Program to Multiply two Matrices. Divide And Conquer Algorithm
|
||||
|
||||
Code :
|
||||
|
||||
|
||||
# include <iostream.h>
|
||||
# include <stdlib.h>
|
||||
# include <conio.h>
|
||||
|
||||
|
||||
|
||||
class Matrix
|
||||
{
|
||||
private:
|
||||
float matrix_a[3][3];
|
||||
float matrix_b[3][3];
|
||||
float matrix_c[3][3];
|
||||
|
||||
public:
|
||||
Matrix( );
|
||||
|
||||
void get_matrix_a( );
|
||||
void get_matrix_b( );
|
||||
void multiply_matrices( );
|
||||
void show_result_Matrix( );
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
Matrix::Matrix( )
|
||||
{
|
||||
for(int i=0;i<3;i++)
|
||||
{
|
||||
for(int j=0;j<3;j++)
|
||||
{
|
||||
matrix_a[i][j]=0;
|
||||
matrix_b[i][j]=0;
|
||||
matrix_c[i][j]=0;
|
||||
}
|
||||
}
|
||||
|
||||
gotoxy(1,1);
|
||||
cout<<"
|
||||
**************************************************************************
|
||||
****"<<endl;
|
||||
cout<<" * * * * * * * * * * * * * * Matrix Multiplication * * *
|
||||
* *
|
||||
* * * * * * * *"<<endl;
|
||||
cout<<"
|
||||
**************************************************************************
|
||||
****"<<endl;
|
||||
|
||||
gotoxy(1,25);
|
||||
cout<<"
|
||||
**************************************************************************
|
||||
****";
|
||||
}
|
||||
|
||||
|
||||
|
||||
void Matrix::get_matrix_a( )
|
||||
{
|
||||
gotoxy(1,6);
|
||||
cout<<" Enter the values of the Matrix A row by row :
|
||||
"<<endl;
|
||||
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
|
||||
gotoxy(18,10);
|
||||
cout<<" A = "<<endl;
|
||||
|
||||
int x=28;
|
||||
int y=9;
|
||||
|
||||
for(int i=0;i<3;i++)
|
||||
{
|
||||
for(int j=0;j<3;j++)
|
||||
{
|
||||
gotoxy(x,y);
|
||||
cin>>matrix_a[i][j];
|
||||
|
||||
x+=5;
|
||||
}
|
||||
|
||||
x=28;
|
||||
y++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
void Matrix::get_matrix_b( )
|
||||
{
|
||||
gotoxy(1,15);
|
||||
cout<<" Enter the values of the Matrix B row by row :
|
||||
"<<endl;
|
||||
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
|
||||
gotoxy(18,19);
|
||||
cout<<" B = "<<endl;
|
||||
|
||||
int x=28;
|
||||
int y=18;
|
||||
|
||||
for(int i=0;i<3;i++)
|
||||
{
|
||||
for(int j=0;j<3;j++)
|
||||
{
|
||||
gotoxy(x,y);
|
||||
cin>>matrix_b[i][j];
|
||||
|
||||
x+=5;
|
||||
}
|
||||
|
||||
x=28;
|
||||
y++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
void Matrix::multiply_matrices( )
|
||||
{
|
||||
for(int i=0;i<3;i++)
|
||||
{
|
||||
for(int j=0;j<3;j++)
|
||||
{
|
||||
float value=0;
|
||||
float sum=0;
|
||||
|
||||
for(int k=0;k<3;k++)
|
||||
{
|
||||
value=matrix_a[j][k]*matrix_b[k][j];
|
||||
sum+=value;
|
||||
}
|
||||
|
||||
matrix_c[i][j]=sum;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
void Matrix::show_result_Matrix( )
|
||||
{
|
||||
clrscr( );
|
||||
|
||||
gotoxy(1,1);
|
||||
cout<<"
|
||||
**************************************************************************
|
||||
****"<<endl;
|
||||
cout<<" * * * * * * * * * * * * * * Matrix Multiplication * * *
|
||||
* *
|
||||
* * * * * * * *"<<endl;
|
||||
cout<<"
|
||||
**************************************************************************
|
||||
****"<<endl;
|
||||
|
||||
gotoxy(1,6);
|
||||
cout<<" The values of Matrix A and B are :"<<endl;
|
||||
|
||||
cout<<" � � �
|
||||
�"<<endl;
|
||||
cout<<" � � �
|
||||
�"<<endl;
|
||||
cout<<" � � �
|
||||
�"<<endl;
|
||||
cout<<" � � �
|
||||
�"<<endl;
|
||||
cout<<" � � � �"<<endl;
|
||||
|
||||
gotoxy(45,9);
|
||||
cout<<" B = "<<endl;
|
||||
|
||||
gotoxy(10,9);
|
||||
cout<<" A = "<<endl;
|
||||
|
||||
gotoxy(1,15);
|
||||
cout<<" The Product of Matrix A and B is :
|
||||
"<<endl;
|
||||
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
cout<<" � �"<<endl;
|
||||
|
||||
gotoxy(13,19);
|
||||
cout<<" A * B = "<<endl;
|
||||
|
||||
int x_1=20;
|
||||
int y_1=8;
|
||||
|
||||
int x_2=55;
|
||||
int y_2=8;
|
||||
|
||||
int x_3=28;
|
||||
int y_3=18;
|
||||
|
||||
for(int i=0;i<3;i++)
|
||||
{
|
||||
for(int j=0;j<3;j++)
|
||||
{
|
||||
gotoxy(x_1,y_1);
|
||||
cout<<matrix_a[i][j];
|
||||
|
||||
gotoxy(x_2,y_2);
|
||||
cout<<matrix_b[i][j];
|
||||
|
||||
gotoxy(x_3,y_3);
|
||||
cout<<matrix_c[i][j];
|
||||
|
||||
x_1+=5;
|
||||
x_2+=5;
|
||||
x_3+=5;
|
||||
}
|
||||
|
||||
x_1=20;
|
||||
y_1++;
|
||||
|
||||
x_2=55;
|
||||
y_2++;
|
||||
|
||||
x_3=28;
|
||||
y_3++;
|
||||
}
|
||||
|
||||
gotoxy(1,25);
|
||||
cout<<"
|
||||
**************************************************************************
|
||||
****";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
int main( )
|
||||
{
|
||||
textmode(BW80);
|
||||
clrscr( );
|
||||
|
||||
Matrix Obj;
|
||||
|
||||
Obj.get_matrix_a( );
|
||||
Obj.get_matrix_b( );
|
||||
Obj.multiply_matrices( );
|
||||
Obj.show_result_Matrix( );
|
||||
|
||||
getch( );
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
A C++ Program to computes the n_th term of the fibonacci series using
|
||||
Divide and Conquer Strategy.
|
||||
|
||||
Code :
|
||||
|
||||
|
||||
# include <iostream.h>
|
||||
# include <conio.h>
|
||||
|
||||
|
||||
//------------------------ Function
|
||||
rototypes ------------------------//
|
||||
|
||||
|
||||
|
||||
const long fibonacci(const int);
|
||||
|
||||
|
||||
//-----------------------------
|
||||
main( ) -------------------------------//
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
clrscr( );
|
||||
|
||||
int number;
|
||||
|
||||
cout<<"
|
||||
Enter the number ( 1 - 25 ) = ";
|
||||
cin>>number;
|
||||
|
||||
number=((number>25)?25:number);
|
||||
|
||||
cout<<"
|
||||
|
||||
The "<<number<<"_th term of fibonacci series =
|
||||
"<<fibonacci(number);
|
||||
|
||||
getch( );
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//------------------------ Function
|
||||
efinitions -----------------------//
|
||||
|
||||
|
||||
|
||||
//----------------------------
|
||||
fibonacci( ) ---------------------------//
|
||||
|
||||
|
||||
/
|
||||
|
||||
const long fibonacci(const int n)
|
||||
{
|
||||
if(n<=1)
|
||||
return n;
|
||||
|
||||
else
|
||||
return (fibonacci(n-1)+fibonacci(n-2));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
A C++ program with several functions
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
void line(), message();
|
||||
int main()
|
||||
{
|
||||
cout << "The program starts in main()." << endl;
|
||||
line();
|
||||
message();
|
||||
line();
|
||||
cout << "At the end of main()." << endl;
|
||||
return 0;
|
||||
}
|
||||
void line()
|
||||
{
|
||||
cout << "line();" << endl;
|
||||
}
|
||||
void message()
|
||||
{
|
||||
cout << "In function message()." << endl;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
A Class as a Member Variable of Another Class
|
||||
This is an example of one object (the shape class implements a rectangle) being a member variable of another object (a brick).
|
||||
|
||||
Header File: shape.h
|
||||
|
||||
#ifndef _SHAPE_H
|
||||
#define _SHAPE_H
|
||||
|
||||
class FRectangle
|
||||
{
|
||||
public:
|
||||
FRectangle(double l = 0, double w = 0)
|
||||
: Length(l), Width(w) {}
|
||||
void setLength(double lgt);
|
||||
void setWidth(double wdt);
|
||||
double getLength() const;
|
||||
double getWidth() const;
|
||||
double Perimeter() const;
|
||||
double Area() const;
|
||||
void Properties();
|
||||
private:
|
||||
double Length;
|
||||
double Width;
|
||||
};
|
||||
|
||||
#endif // _SHAPE_H
|
||||
|
||||
Source File: shape.cpp
|
||||
|
||||
#include <iostream.h>
|
||||
#include "shape.h"
|
||||
|
||||
void FRectangle::setLength(double lgt)
|
||||
{
|
||||
Length = lgt;
|
||||
}
|
||||
|
||||
void FRectangle::setWidth(double wdt)
|
||||
{
|
||||
Width = wdt;
|
||||
}
|
||||
|
||||
double FRectangle::getLength() const
|
||||
{
|
||||
return Length;
|
||||
}
|
||||
|
||||
double FRectangle::getWidth() const
|
||||
{
|
||||
return Width;
|
||||
}
|
||||
|
||||
double FRectangle::Perimeter() const
|
||||
{
|
||||
return 2 * (Length + Width);
|
||||
}
|
||||
|
||||
double FRectangle::Area() const
|
||||
{
|
||||
return Length * Width;
|
||||
}
|
||||
|
||||
void FRectangle::Properties()
|
||||
{
|
||||
cout << "\nRectangle characteristics";
|
||||
cout << "\n\tLength = " << Length;
|
||||
cout << "\n\tWidth = " << Width;
|
||||
cout << "\n\tPerimeter = " << Perimeter();
|
||||
cout << "\n\tArea = " << Area() << endl;
|
||||
}
|
||||
|
||||
Header File: brick.h
|
||||
|
||||
#ifndef BRICK_H_
|
||||
#define BRICK_H_
|
||||
|
||||
#include "shape.h"
|
||||
|
||||
class Brick
|
||||
{
|
||||
public:
|
||||
Brick() {}
|
||||
void setThickness(double Tck);
|
||||
void setDimensions(double l, double w, double t);
|
||||
void setColor(char* clr);
|
||||
void setTexture(char* txr);
|
||||
char* getColor() const;
|
||||
char* getTexture() const;
|
||||
double Volume() const;
|
||||
void Display();
|
||||
private:
|
||||
FRectangle shape;
|
||||
char* Color;
|
||||
char* Texture;
|
||||
double Thickness;
|
||||
};
|
||||
|
||||
#endif // BRICK_H_
|
||||
|
||||
Source File: brick.cpp
|
||||
|
||||
#include <iostream.h>
|
||||
#include "brick.h"
|
||||
|
||||
void Brick::setThickness(double Tck)
|
||||
{
|
||||
Thickness = Tck;
|
||||
}
|
||||
|
||||
void Brick::setColor(char* clr)
|
||||
{
|
||||
Color = clr;
|
||||
}
|
||||
|
||||
void Brick::setTexture(char* txr)
|
||||
{
|
||||
Texture = txr;
|
||||
}
|
||||
|
||||
void Brick::setDimensions(double l, double w, double t)
|
||||
{
|
||||
shape.setLength(l);
|
||||
shape.setWidth(w);
|
||||
setThickness(t);
|
||||
}
|
||||
|
||||
char* Brick::getColor() const
|
||||
{
|
||||
return Color;
|
||||
}
|
||||
|
||||
char* Brick::getTexture() const
|
||||
{
|
||||
return Texture;
|
||||
}
|
||||
|
||||
double Brick::Volume() const
|
||||
{
|
||||
return shape.getLength() * shape.getWidth() * Thickness;
|
||||
}
|
||||
|
||||
void Brick::Display()
|
||||
{
|
||||
cout << "\nBrick characteristics";
|
||||
cout << "\n\tLength = " << shape.getLength();
|
||||
cout << "\n\tWidth = " << shape.getWidth();
|
||||
cout << "\n\tArea = " << shape.Area();
|
||||
cout << "\n\tVolume = " << Volume();
|
||||
cout << "\n\tColor = " << getColor();
|
||||
cout << "\n\tTextture = " << getTexture();
|
||||
cout << endl;
|
||||
}
|
||||
|
||||
Main File: Exo.cpp
|
||||
|
||||
#include "shape.h"
|
||||
#include "brick.h"
|
||||
|
||||
void main()
|
||||
{
|
||||
Brick brick;
|
||||
|
||||
brick.setDimensions(12.50, 8.75, 5.55);
|
||||
brick.setColor("Bone White");
|
||||
brick.setTexture("Early Breeze");
|
||||
|
||||
brick.Display();
|
||||
}
|
||||
|
||||
Here is an example of running the program:
|
||||
|
||||
Brick characteristics
|
||||
Length = 12.5
|
||||
Width = 8.75
|
||||
Area = 109.375
|
||||
Volume = 607.031
|
||||
Color = Bone White
|
||||
Textture = Early Breeze
|
||||
@@ -0,0 +1,26 @@
|
||||
A Closer Look at the I/O Operators
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
float f;
|
||||
|
||||
char str[80];
|
||||
|
||||
double d;
|
||||
|
||||
cout << "Enter two floating point numbers: ";
|
||||
|
||||
cin >> f >> d;
|
||||
|
||||
cout << "Enter a string: ";
|
||||
|
||||
cin >> str;
|
||||
|
||||
cout << f << " " << d << " " << str;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
A Simple for Statement - generate the square root of 1 to 10
|
||||
|
||||
#include <iostream>
|
||||
#include <math.h> // for newer compilers, use <cmath>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int num;
|
||||
double sq_root;
|
||||
|
||||
for(num=1; num < 10; num++) {
|
||||
sq_root = sqrt((double) num); //casting num from integer to double
|
||||
// then taking its square root
|
||||
cout << num << " " << sq_root << '\n';
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
A Simple if Statement
|
||||
This program illustrates a simple if statement.
|
||||
It reads in two integers and prints out a
|
||||
message on the screen according to their values.
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int a, b;
|
||||
|
||||
cout << "Enter first number: ";
|
||||
cin >> a;
|
||||
cout << "Enter second number: ";
|
||||
cin >> b;
|
||||
|
||||
if(a < b)
|
||||
cout << "First number is less than second.\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
A Simple program finding the absolute value of an integer
|
||||
A Simple program without using functions
|
||||
|
||||
This program find the absolute value of an integer without using a function
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int number;
|
||||
int abs_number;
|
||||
|
||||
// Ask for input
|
||||
cout << "This program finds the absolute value of an integer." << endl;
|
||||
cout << "Enter an integer (positive or negative): ";
|
||||
cin >> number;
|
||||
|
||||
// Find the absolute value
|
||||
if(number >= 0)
|
||||
{
|
||||
abs_number = number;
|
||||
}
|
||||
else
|
||||
abs_number = -number;
|
||||
|
||||
// Print out output
|
||||
cout << "The absolute value of " << number << " is " << abs_number;
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
||||
|
||||
The same program using function
|
||||
|
||||
This program finds the absolute value of an integer using a function
|
||||
|
||||
int Abs(int i); // Function prototype
|
||||
int main()
|
||||
{
|
||||
int number;
|
||||
int abs_number;
|
||||
|
||||
cout << "This program finds the absolute value of an integer." << endl;
|
||||
cout << "Enter an integer (positive or negative): ";
|
||||
cin >> number;
|
||||
|
||||
// Calling the function Abs()
|
||||
abs_number = Abs(number);
|
||||
cout << "The absolute value of " << number << " is " << abs_number;
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
||||
// Function definition
|
||||
int Abs(int i)
|
||||
{
|
||||
if( i >= 0)
|
||||
return i;
|
||||
else
|
||||
return -i;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
A base pointer to access derived objects
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
class BaseClass {
|
||||
int i;
|
||||
public:
|
||||
void setInt(int num) {
|
||||
i = num;
|
||||
}
|
||||
int getInt() {
|
||||
return i;
|
||||
}
|
||||
};
|
||||
class derived: public BaseClass {
|
||||
int j;
|
||||
public:
|
||||
void setJ(int num) {
|
||||
j = num;
|
||||
}
|
||||
int getJ() {
|
||||
return j;
|
||||
}
|
||||
};
|
||||
int main()
|
||||
{
|
||||
BaseClass *baseClassPointer;
|
||||
derived d;
|
||||
baseClassPointer = &d; // BaseClass pointer points to derived object
|
||||
// access derived object using BaseClass pointer
|
||||
baseClassPointer->setInt(10);
|
||||
cout << baseClassPointer->getInt() << " ";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
A classical stack operation using a string of characters.
|
||||
#include <iostream>
|
||||
#include <string.h>
|
||||
using namespace std;
|
||||
#define maxlen 80
|
||||
|
||||
class stack {
|
||||
char str1[maxlen];
|
||||
int first;
|
||||
public:
|
||||
void clear(void);
|
||||
char top(void);
|
||||
int empty(void);
|
||||
int full(void);
|
||||
void push(char chr);
|
||||
char pop(void);
|
||||
};
|
||||
|
||||
void stack::clear(void)
|
||||
{
|
||||
first=0;
|
||||
}
|
||||
char stack::top(void)
|
||||
{
|
||||
return (str1[first]);
|
||||
}
|
||||
|
||||
int stack::empty(void)
|
||||
{
|
||||
return (first==0);
|
||||
}
|
||||
|
||||
int stack::full(void)
|
||||
{
|
||||
return (first==maxlen-1);
|
||||
}
|
||||
|
||||
void stack::push(char chr)
|
||||
{
|
||||
str1[++first]=chr;
|
||||
}
|
||||
char stack::pop(void)
|
||||
{
|
||||
return (str1[first-1]);
|
||||
}
|
||||
|
||||
main( )
|
||||
{
|
||||
stack mystack;
|
||||
char str[11]="0123456789";
|
||||
|
||||
mystack.clear( );
|
||||
|
||||
for(int i=0; (int) i<strlen(str);i++) {
|
||||
if (!mystack.full( ))
|
||||
mystack.push(str[i]);
|
||||
cout << str[i] << endl;
|
||||
}
|
||||
while (!mystack.empty( ))
|
||||
cout << mystack.pop( ) << endl;
|
||||
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
A classical stack operation using a string of characters.
|
||||
#include <iostream>
|
||||
#include <string.h>
|
||||
using namespace std;
|
||||
#define maxlen 80
|
||||
|
||||
class stack {
|
||||
char str1[maxlen];
|
||||
int first;
|
||||
public:
|
||||
void clear(void);
|
||||
char top(void);
|
||||
int empty(void);
|
||||
int full(void);
|
||||
void push(char chr);
|
||||
char pop(void);
|
||||
};
|
||||
|
||||
void stack::clear(void)
|
||||
{
|
||||
first=0;
|
||||
}
|
||||
char stack::top(void)
|
||||
{
|
||||
return (str1[first]);
|
||||
}
|
||||
|
||||
int stack::empty(void)
|
||||
{
|
||||
return (first==0);
|
||||
}
|
||||
|
||||
int stack::full(void)
|
||||
{
|
||||
return (first==maxlen-1);
|
||||
}
|
||||
|
||||
void stack::push(char chr)
|
||||
{
|
||||
str1[++first]=chr;
|
||||
}
|
||||
char stack::pop(void)
|
||||
{
|
||||
return (str1[first-1]);
|
||||
}
|
||||
|
||||
main( )
|
||||
{
|
||||
stack mystack;
|
||||
char str[11]="0123456789";
|
||||
|
||||
mystack.clear( );
|
||||
|
||||
for(int i=0; (int) i<strlen(str);i++) {
|
||||
if (!mystack.full( ))
|
||||
mystack.push(str[i]);
|
||||
cout << str[i] << endl;
|
||||
}
|
||||
while (!mystack.empty( ))
|
||||
cout << mystack.pop( ) << endl;
|
||||
|
||||
return (0);
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
A copy constructor to allow StringClass objects to be passed to functions.
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
using namespace std;
|
||||
|
||||
class StringClass {
|
||||
char *p;
|
||||
public:
|
||||
StringClass(char *s); // constructor
|
||||
StringClass(const StringClass &o); // copy constructor
|
||||
~StringClass() { // destructor
|
||||
delete [] p;
|
||||
}
|
||||
char *get() {
|
||||
return p;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
StringClass::StringClass(char *s) // "Normal" constructor
|
||||
{
|
||||
int l;
|
||||
|
||||
l = strlen(s)+1;
|
||||
|
||||
p = new char [l];
|
||||
if(!p) {
|
||||
cout << "Allocation error\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
strcpy(p, s);
|
||||
}
|
||||
|
||||
|
||||
StringClass::StringClass(const StringClass &o) // Copy constructor
|
||||
{
|
||||
int l;
|
||||
|
||||
l = strlen(o.p)+1;
|
||||
|
||||
p = new char [l]; // allocate memory for new copy
|
||||
if(!p) {
|
||||
cout << "Allocation error\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
strcpy(p, o.p); // copy string into copy
|
||||
}
|
||||
|
||||
void show(StringClass x)
|
||||
{
|
||||
char *s;
|
||||
|
||||
s = x.get();
|
||||
cout << s << endl;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
StringClass a("Hello World"), b("Hello World");
|
||||
|
||||
show(a);
|
||||
show(b);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
A filter to remove white-space characters at the ends of lines.
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
void cutline( void );
|
||||
string line;
|
||||
int main()
|
||||
{
|
||||
while( getline(cin, line)) {
|
||||
cutline();
|
||||
cout << line << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void cutline()
|
||||
{
|
||||
int i = line.size();
|
||||
|
||||
while( i-- >= 0 )
|
||||
if( line[i] != ' ' && line[i] != '\t' )
|
||||
break;
|
||||
line.resize(++i);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
A four-function postfix calculator.
|
||||
#include <iostream>
|
||||
#include <stack>
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
stack<double> stackObject;
|
||||
double a, b;
|
||||
string s;
|
||||
|
||||
do {
|
||||
cout << ": ";
|
||||
cin >> s;
|
||||
switch( s[ 0 ]) {
|
||||
case 'q': // quit the calculator
|
||||
break;
|
||||
case '.': // show top-of-stack
|
||||
cout << stackObject.top() << endl;
|
||||
break;
|
||||
case '+': // add
|
||||
if(stackObject.size() < 2) {
|
||||
cout << "Operand Missing\n";
|
||||
break;
|
||||
}
|
||||
|
||||
a = stackObject.top();
|
||||
stackObject.pop();
|
||||
b = stackObject.top();
|
||||
stackObject.pop();
|
||||
cout << a + b << endl;
|
||||
stackObject.push(a + b);
|
||||
break;
|
||||
case '-': // subtract
|
||||
// see if user entering a negative number
|
||||
if(s.size() != 1) {
|
||||
// push value onto the stack
|
||||
stackObject.push(atof(s.c_str()));
|
||||
break;
|
||||
}
|
||||
|
||||
// otherwise, is a subtraction
|
||||
if(stackObject.size() < 2) {
|
||||
cout << "Operand Missing\n";
|
||||
break;
|
||||
}
|
||||
|
||||
a = stackObject.top();
|
||||
stackObject.pop();
|
||||
b = stackObject.top();
|
||||
stackObject.pop();
|
||||
cout << b - a << endl;
|
||||
stackObject.push(b - a);
|
||||
break;
|
||||
case '*': // multiply
|
||||
if(stackObject.size() < 2) {
|
||||
cout << "Operand Missing\n";
|
||||
break;
|
||||
}
|
||||
|
||||
a = stackObject.top();
|
||||
stackObject.pop();
|
||||
b = stackObject.top();
|
||||
stackObject.pop();
|
||||
cout << a*b << endl;
|
||||
stackObject.push(a*b);
|
||||
break;
|
||||
case '/': // divide
|
||||
if(stackObject.size() < 2) {
|
||||
cout << "Operand Missing\n";
|
||||
break;
|
||||
}
|
||||
|
||||
a = stackObject.top();
|
||||
stackObject.pop();
|
||||
b = stackObject.top();
|
||||
stackObject.pop();
|
||||
cout << b/a << endl;
|
||||
stackObject.push(b/a);
|
||||
break;
|
||||
default:
|
||||
// push value onto the stack
|
||||
stackObject.push(atof(s.c_str()));
|
||||
break;
|
||||
}
|
||||
} while(s != "q");
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
A function object that computes an integer sum.
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
using namespace std;
|
||||
|
||||
class sum : unary_function<int, void> {
|
||||
public:
|
||||
argument_type sum;
|
||||
|
||||
sum() { sum = 0; }
|
||||
|
||||
result_type operator()(argument_type i) {
|
||||
sum += i;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<int> v;
|
||||
|
||||
for(int i=1; i < 11; i++) v.push_back(i);
|
||||
|
||||
for(unsigned i=0; i < v.size(); ++i){
|
||||
cout << v[i] << endl;
|
||||
}
|
||||
sum s;
|
||||
|
||||
s = for_each(v.begin(), v.end(), sum());
|
||||
cout << "sum of v: " << s.sum << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
A generic bubble sort.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
template <class X> void bubble(X *data, int size)
|
||||
{
|
||||
register int a, b;
|
||||
X t;
|
||||
|
||||
for(a=1; a < size; a++)
|
||||
for(b=size-1; b >= a; b--)
|
||||
if(data[b-1] > data[b]) {
|
||||
t = data[b-1];
|
||||
data[b-1] = data[b];
|
||||
data[b] = t;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int i[] = {3, 2, 5, 6, 1, 8, 9, 3, 6, 9};
|
||||
double d[] = {1.2, 5.5, 2.2, 3.3};
|
||||
int j;
|
||||
|
||||
bubble(i, 10); // sort ints
|
||||
bubble(d, 4); // sort doubles
|
||||
|
||||
for(j=0; j<10; j++)
|
||||
cout << i[j] << ' ';
|
||||
cout << endl;
|
||||
|
||||
for(j=0; j<4; j++)
|
||||
cout << d[j] << ' ';
|
||||
cout << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
A generic mode finding function.
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
using namespace std;
|
||||
|
||||
|
||||
template <class X> X mode(X *data, int size)
|
||||
{
|
||||
register int t, w;
|
||||
X md, oldmd;
|
||||
int count, oldcount;
|
||||
|
||||
oldmd = 0;
|
||||
oldcount = 0;
|
||||
for(t=0; t<size; t++) {
|
||||
md = data[t];
|
||||
count = 1;
|
||||
for(w = t+1; w < size; w++)
|
||||
if(md==data[w]) count++;
|
||||
if(count > oldcount) {
|
||||
oldmd = md;
|
||||
oldcount = count;
|
||||
}
|
||||
}
|
||||
return oldmd;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int i[] = { 1, 2, 3, 4, 2, 3, 2, 2, 1, 5};
|
||||
char *p = "this is a test";
|
||||
|
||||
cout << "mode of i: " << mode(i, 10) << endl;
|
||||
cout << "mode of p: " << mode(p, (int) strlen(p));
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
A generic stack class
|
||||
|
||||
#include <iostream>
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
#if !defined __STACK_H
|
||||
#define __STACK_H
|
||||
|
||||
namespace stk{
|
||||
template<class T>
|
||||
class Stack; // Forward declaration of Stack class for overloaded <<
|
||||
operator
|
||||
|
||||
template<class T>
|
||||
ostream& operator<<(ostream &,Stack<T> &); // template declaration of
|
||||
<<
|
||||
operator
|
||||
|
||||
template<class T>
|
||||
class Stack{
|
||||
private:
|
||||
T *p;
|
||||
int top,length;
|
||||
|
||||
string str()const;
|
||||
public:
|
||||
Stack();
|
||||
Stack(const int);
|
||||
Stack(const Stack<T>&);
|
||||
~Stack();
|
||||
|
||||
void push(T);
|
||||
T pop();
|
||||
int get_length()const;
|
||||
bool is_empty()const;
|
||||
Stack<T> operator=(const Stack<T>&);
|
||||
|
||||
// only for basic types
|
||||
friend ostream& operator<< <>(ostream&,Stack<T> &);
|
||||
|
||||
class StackException{
|
||||
private:
|
||||
string desc;
|
||||
public:
|
||||
StackException(string exp){ desc="Exception : "+exp; }
|
||||
string get_exp(){ return desc; }
|
||||
};
|
||||
};
|
||||
|
||||
template<class T>
|
||||
Stack<T>::Stack(){
|
||||
top=-1;
|
||||
length=0;
|
||||
p=0;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
Stack<T>::Stack(const int size){
|
||||
top=-1;
|
||||
length=size;
|
||||
try{
|
||||
p=new T[length];
|
||||
}catch(bad_alloc ba){
|
||||
cout<<"Memory can not be alllocated
|
||||
";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
template<class T>
|
||||
Stack<T>::Stack(const Stack<T> &o){
|
||||
top=o.top;
|
||||
length=o.length;
|
||||
try{
|
||||
p=new T[length];
|
||||
}catch(bad_alloc ba){
|
||||
cout<<"Memory allocation failed
|
||||
";
|
||||
return;
|
||||
}
|
||||
for(int i=0;i<length;i++)
|
||||
p[i]=o.p[i];
|
||||
}
|
||||
|
||||
template<class T>
|
||||
Stack<T>::~Stack(){
|
||||
if(p!=0)
|
||||
delete [] p;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
void Stack<T>::push(T elem){
|
||||
if(p==0){
|
||||
try{
|
||||
p=new T[1];
|
||||
}catch(bad_alloc ba){
|
||||
throw StackException("Memory fault
|
||||
");
|
||||
}
|
||||
length++;
|
||||
top++;
|
||||
p[top]=elem;
|
||||
}
|
||||
else if(top==(length-1)){
|
||||
T *q;
|
||||
try{
|
||||
q=new T[length+1];
|
||||
}catch(bad_alloc ba1){
|
||||
throw StackException("Memory fault
|
||||
");
|
||||
}
|
||||
for(int i=0;i<length;i++)
|
||||
q[i]=p[i];
|
||||
length++;
|
||||
top++;
|
||||
q[top]=elem;
|
||||
delete [] p;
|
||||
p=q;
|
||||
}
|
||||
else{
|
||||
top++;
|
||||
p[top]=elem;
|
||||
}
|
||||
}
|
||||
|
||||
template<class T>
|
||||
T Stack<T>::pop(){
|
||||
if(p==0 || top==-1){
|
||||
throw StackException("Stack empty!
|
||||
");
|
||||
}
|
||||
T ret=p[top];
|
||||
top--;
|
||||
length--;
|
||||
|
||||
if(top==-1){
|
||||
delete [] p;
|
||||
p=0;
|
||||
}
|
||||
else{
|
||||
T *q;
|
||||
try{
|
||||
q=new T[length];
|
||||
}catch(bad_alloc ba){
|
||||
throw StackException("Memory fault
|
||||
");
|
||||
}
|
||||
for(int i=0;i<length;i++)
|
||||
q[i]=p[i];
|
||||
delete [] p;
|
||||
p=q;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
int Stack<T>::get_length()const{
|
||||
return length;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
bool Stack<T>::is_empty()const{
|
||||
return ((p==0)? true : false);
|
||||
}
|
||||
|
||||
template<class T>
|
||||
string Stack<T>::str()const{ // private member function
|
||||
if(p==0)
|
||||
return string("");
|
||||
stringstream ss;
|
||||
for(int i=0;i<length;i++){
|
||||
ss << p[i];
|
||||
if(i!=(length-1))
|
||||
ss << ", ";
|
||||
}
|
||||
//ss<<"
|
||||
";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
template<class T>
|
||||
Stack<T> Stack<T>::operator=(const Stack<T> &stk){
|
||||
length=stk.length;
|
||||
top=stk.top;
|
||||
|
||||
if(p!=0)
|
||||
delete [] p;
|
||||
try{
|
||||
p=new T[length];
|
||||
}catch(bad_alloc ba){
|
||||
throw StackException("Memory fault in copying!
|
||||
");
|
||||
}
|
||||
for(int i=0;i<length;i++)
|
||||
p[i]=stk.p[i];
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
ostream& operator<<(ostream &o,Stack<T> &s){
|
||||
o<<s.str();
|
||||
return o;
|
||||
}
|
||||
|
||||
} // namespace stk;
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,91 @@
|
||||
A generic stack that holds two values.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
#define SIZE 10
|
||||
|
||||
template <class StackType> class stack {
|
||||
StackType stck[SIZE][2];
|
||||
int topOfStack;
|
||||
|
||||
public:
|
||||
void init() { topOfStack = 0; }
|
||||
void push(StackType ob, StackType object2);
|
||||
StackType pop(StackType &object2);
|
||||
};
|
||||
|
||||
template <class StackType>
|
||||
void stack<StackType>::push(StackType ob, StackType object2)
|
||||
{
|
||||
if(topOfStack==SIZE) {
|
||||
cout << "Stack is full.\n";
|
||||
return;
|
||||
}
|
||||
stck[topOfStack][0] = ob;
|
||||
stck[topOfStack][1] = object2;
|
||||
topOfStack++;
|
||||
}
|
||||
|
||||
template <class StackType>
|
||||
StackType stack<StackType>::pop(StackType &object2)
|
||||
{
|
||||
if(topOfStack==0) {
|
||||
cout << "Stack is empty.\n";
|
||||
return 0;
|
||||
}
|
||||
topOfStack--;
|
||||
object2 = stck[topOfStack][1];
|
||||
return stck[topOfStack][0];
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
stack<char> stack1, stackObject2;
|
||||
int i;
|
||||
char ch;
|
||||
|
||||
stack1.init();
|
||||
stackObject2.init();
|
||||
|
||||
stack1.push('a', 'b');
|
||||
stackObject2.push('x', 'z');
|
||||
stack1.push('b', 'd');
|
||||
stackObject2.push('y', 'e');
|
||||
stack1.push('c', 'a');
|
||||
stackObject2.push('z', 'x');
|
||||
|
||||
for(i = 0; i <3; i++) {
|
||||
cout << "Pop stack1: " << stack1.pop(ch);
|
||||
cout << ' ' << ch << endl;
|
||||
}
|
||||
for(i = 0; i <3; i++) {
|
||||
cout << "Pop stackObject2: " << stackObject2.pop(ch);
|
||||
cout << ' ' << ch << endl;
|
||||
}
|
||||
|
||||
// demonstrate double stacks
|
||||
stack<double> doubleValueStack1, doubleValueStack2; // create two stacks
|
||||
double d;
|
||||
|
||||
doubleValueStack1.init();
|
||||
doubleValueStack2.init();
|
||||
|
||||
doubleValueStack1.push(1.1, 2.0);
|
||||
doubleValueStack2.push(2.2, 3.0);
|
||||
doubleValueStack1.push(3.3, 4.0);
|
||||
doubleValueStack2.push(4.4, 5.0);
|
||||
doubleValueStack1.push(5.5, 6.0);
|
||||
doubleValueStack2.push(6.6, 7.0);
|
||||
|
||||
for(i = 0; i <3; i++) {
|
||||
cout << "Pop doubleValueStack1: " << doubleValueStack1.pop(d);
|
||||
cout << ' '<< d << endl;
|
||||
}
|
||||
|
||||
for(i = 0; i <3; i++) {
|
||||
cout << "Pop doubleValueStack2: " << doubleValueStack2.pop(d);
|
||||
cout << ' '<< d << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
A generic stack that includes exception handling.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
#define SIZE 10
|
||||
|
||||
template <class StackType> class stack {
|
||||
StackType stck[SIZE];
|
||||
int topOfStack;
|
||||
|
||||
public:
|
||||
void init() {
|
||||
topOfStack = 0;
|
||||
}
|
||||
void push(StackType ch);
|
||||
StackType pop();
|
||||
};
|
||||
|
||||
template <class StackType>
|
||||
void stack<StackType>::push(StackType ob)
|
||||
{
|
||||
try {
|
||||
if(topOfStack==SIZE) throw SIZE;
|
||||
} catch(int) {
|
||||
cout << "Stack is full.\n";
|
||||
return;
|
||||
}
|
||||
stck[topOfStack] = ob;
|
||||
topOfStack++;
|
||||
}
|
||||
|
||||
template <class StackType>
|
||||
StackType stack<StackType>::pop()
|
||||
{
|
||||
try {
|
||||
if( topOfStack == 0)
|
||||
throw 0;
|
||||
} catch(int) {
|
||||
cout << "Stack is empty.\n";
|
||||
return 0;
|
||||
}
|
||||
topOfStack--;
|
||||
return stck[topOfStack];
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
stack<char> stack1, stack2;
|
||||
int i;
|
||||
|
||||
stack1.init();
|
||||
stack2.init();
|
||||
|
||||
stack1.push('a');
|
||||
stack2.push('x');
|
||||
stack1.push('b');
|
||||
stack2.push('y');
|
||||
stack1.push('c');
|
||||
stack2.push('z');
|
||||
|
||||
for(i = 0; i <3; i++)
|
||||
cout << "Pop stack1: " << stack1.pop() << endl;
|
||||
for(i = 0; i <4; i++)
|
||||
cout << "Pop stack2: " << stack2.pop() << endl;
|
||||
|
||||
// demonstrate double stacks
|
||||
stack<double> doubleValueStack1, doubleValueStack2; // create two stacks
|
||||
|
||||
// initialize the stacks
|
||||
doubleValueStack1.init();
|
||||
doubleValueStack2.init();
|
||||
|
||||
doubleValueStack1.push(1.1);
|
||||
doubleValueStack2.push(2.2);
|
||||
doubleValueStack1.push(3.3);
|
||||
doubleValueStack2.push(4.4);
|
||||
doubleValueStack1.push(5.5);
|
||||
doubleValueStack2.push(6.6);
|
||||
|
||||
for(i = 0; i <3; i++)
|
||||
cout << "Pop doubleValueStack1: " << doubleValueStack1.pop() << endl;
|
||||
for(i = 0; i <4; i++)
|
||||
cout << "Pop doubleValueStack2: " << doubleValueStack2.pop() << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
A generic version of myabs().
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
template <class X> X myabs(X val)
|
||||
{
|
||||
return val < 0 ? -val : val;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
cout << myabs(-10) << '\n'; // integer abs
|
||||
|
||||
cout << myabs(-10.0) << '\n'; // double abs
|
||||
|
||||
cout << myabs(-10L) << '\n'; // long abs
|
||||
|
||||
cout << myabs(-10.0F) << '\n'; // float abs
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
A list splicing example.
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
list<string> sentence;
|
||||
list<string> phrase;
|
||||
list<string>::iterator p;
|
||||
|
||||
string s1[] = {"A", "B", ""};
|
||||
string s2[] = {"C", "D", ""};
|
||||
string s3[] = {"E", "F", "G.", ""};
|
||||
string s4[] = {"A", "C,", "E", "G", ""};
|
||||
int i;
|
||||
|
||||
for(i = 0; s1[ i ] != ""; i++)
|
||||
sentence.push_back(s1[i]);
|
||||
|
||||
|
||||
for(i = 0; s2[ i ] != ""; i++)
|
||||
phrase.push_back(s2[ i ]);
|
||||
|
||||
cout << "Original sentence:\n";
|
||||
p = sentence.begin();
|
||||
while(p != sentence.end())
|
||||
cout << *p++ << " ";
|
||||
cout << endl;
|
||||
|
||||
sentence.splice(sentence.begin(), phrase);
|
||||
|
||||
cout << "Sentence after splicing at the front:\n";
|
||||
p = sentence.begin();
|
||||
while(p != sentence.end())
|
||||
cout << *p++ << " ";
|
||||
cout << endl;
|
||||
|
||||
for(i = 0; s3[ i ] != ""; i++)
|
||||
phrase.push_back(s3[ i ]);
|
||||
|
||||
sentence.splice(sentence.end(), phrase);
|
||||
|
||||
cout << "Sentence after splicing at the end:\n";
|
||||
p = sentence.begin();
|
||||
while(p != sentence.end())
|
||||
cout << *p++ << " ";
|
||||
cout << endl;
|
||||
|
||||
for(i = 0; s4[ i ] != ""; i++)
|
||||
phrase.push_back(s4[ i ]);
|
||||
|
||||
|
||||
p = find(sentence.begin(), sentence.end(), "or");
|
||||
sentence.splice(p, phrase);
|
||||
|
||||
cout << "Sentence after splicing in the middle:\n";
|
||||
p = sentence.begin();
|
||||
while(p != sentence.end())
|
||||
cout << *p++ << " ";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
A map: insert pair, find, end
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
map<char, int> mapObject;
|
||||
int i;
|
||||
|
||||
for(i = 0; i <10; i++) {
|
||||
mapObject.insert(pair<char, int>('A'+i, i));
|
||||
}
|
||||
|
||||
char ch;
|
||||
cout << "Enter key: ";
|
||||
cin >> ch;
|
||||
|
||||
map<char, int>::iterator p;
|
||||
|
||||
p = mapObject.find(ch);
|
||||
if(p != mapObject.end())
|
||||
cout << p->second;
|
||||
else
|
||||
cout << "Key not in map.\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
A map of opposites.
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <cstring>
|
||||
using namespace std;
|
||||
|
||||
class StringClass {
|
||||
char str[20];
|
||||
public:
|
||||
StringClass() {
|
||||
strcpy(str, "");
|
||||
}
|
||||
StringClass(char *s) {
|
||||
strcpy(str, s);
|
||||
}
|
||||
char *get() {
|
||||
return str;
|
||||
}
|
||||
};
|
||||
|
||||
// must define less than relative to StringClass objects
|
||||
bool operator<(StringClass a, StringClass b)
|
||||
{
|
||||
return strcmp(a.get(), b.get()) < 0;
|
||||
}
|
||||
|
||||
class opposite {
|
||||
char str[20];
|
||||
public:
|
||||
opposite() {
|
||||
strcmp(str, "");
|
||||
}
|
||||
opposite(char *s) {
|
||||
strcpy(str, s);
|
||||
}
|
||||
char *get() {
|
||||
return str;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
map<StringClass, opposite> mapObject;
|
||||
|
||||
mapObject.insert(pair<StringClass, opposite>(StringClass("yes"), opposite("no")));
|
||||
mapObject.insert(pair<StringClass, opposite>(StringClass("good"), opposite("bad")));
|
||||
mapObject.insert(pair<StringClass, opposite>(StringClass("left"), opposite("right")));
|
||||
mapObject.insert(pair<StringClass, opposite>(StringClass("up"), opposite("down")));
|
||||
|
||||
char str[80];
|
||||
cout << "Enter word: ";
|
||||
cin >> str;
|
||||
|
||||
map<StringClass, opposite>::iterator p;
|
||||
|
||||
p = mapObject.find(StringClass(str));
|
||||
if(p != mapObject.end())
|
||||
cout << "Opposite: " << p->second.get();
|
||||
else
|
||||
cout << "Word not in map.\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
A map of word opposites, using strings.
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
map<string, string> mapObject;
|
||||
int i;
|
||||
|
||||
mapObject.insert(pair<string, string>("yes", "no"));
|
||||
mapObject.insert(pair<string, string>("up", "down"));
|
||||
mapObject.insert(pair<string, string>("left", "right"));
|
||||
mapObject.insert(pair<string, string>("good", "bad"));
|
||||
|
||||
string s;
|
||||
cout << "Enter word: ";
|
||||
cin >> s;
|
||||
|
||||
map<string, string>::iterator p;
|
||||
|
||||
p = mapObject.find(s);
|
||||
if(p != mapObject.end())
|
||||
cout << "Opposite: " << p->second;
|
||||
else
|
||||
cout << "Word not in map.\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
A namespace can be nested within another
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
namespace MyNameSpace1 {
|
||||
int i;
|
||||
namespace MyNameSpace2 { // a nested namespace
|
||||
int j;
|
||||
}
|
||||
}
|
||||
int main()
|
||||
{
|
||||
MyNameSpace1::i = 19;
|
||||
|
||||
MyNameSpace1::MyNameSpace2::j = 10;
|
||||
cout << MyNameSpace1::i << " "<< MyNameSpace1::MyNameSpace2::j << "\n";
|
||||
|
||||
using namespace MyNameSpace1;
|
||||
cout << i * MyNameSpace2::j;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
A shared resource example.
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
using namespace std;
|
||||
|
||||
class output {
|
||||
static char sharedResource[255]; // this is the shared resource
|
||||
static int inuse; // buffer available if 0; in use otherwise
|
||||
static int oindex; // index of sharedResource
|
||||
char str[80];
|
||||
int i; // index of next char in str
|
||||
int who; // identifies the object, must be > 0
|
||||
public:
|
||||
output(int w, char *s) {
|
||||
strcpy(str, s);
|
||||
i = 0;
|
||||
who = w;
|
||||
}
|
||||
|
||||
int putbuf()
|
||||
{
|
||||
if(!str[ i ]) { // done outputting
|
||||
inuse = 0; // release buffer
|
||||
return 0; // signal termination
|
||||
}
|
||||
if(!inuse) // get buffer
|
||||
inuse = who;
|
||||
if(inuse != who) // in use by someone else
|
||||
return -1;
|
||||
if(str[ i ]) { // still chars to output
|
||||
sharedResource[oindex] = str[ i ];
|
||||
i++; oindex++;
|
||||
sharedResource[oindex] = '\0';// always keep null-terminated
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
void show() {
|
||||
cout << sharedResource << '\n';
|
||||
}
|
||||
};
|
||||
|
||||
char output::sharedResource[255]; // this is the shared resource
|
||||
int output::inuse = 0; // buffer available if 0; in use otherwise
|
||||
int output::oindex = 0; // index of sharedResource
|
||||
|
||||
int main()
|
||||
{
|
||||
output object1(1, "This is a test"), object2(2, " of statics");
|
||||
|
||||
while(object1.putbuf() | object2.putbuf()) ; // output chars
|
||||
|
||||
object1.show();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
A short string demonstration.
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
string str1("A");
|
||||
string str2("B");
|
||||
string str3("O");
|
||||
string str4;
|
||||
|
||||
str4 = str1;
|
||||
cout << str1 << "\n" << str3 << "\n";
|
||||
|
||||
str4 = str1 + str2;
|
||||
cout << str4 << "\n";
|
||||
|
||||
str4 = str1 + " to " + str3;
|
||||
cout << str4 << "\n";
|
||||
|
||||
if(str3 > str1)
|
||||
cout << "str3 > str1\n";
|
||||
if(str3 == str1+str2)
|
||||
cout << "str3 == str1+str2\n";
|
||||
|
||||
str1 = "This is a null-terminated string.\n";
|
||||
cout << str1;
|
||||
|
||||
string str5(str1);
|
||||
cout << str5;
|
||||
|
||||
cout << "Enter a string: ";
|
||||
cin >> str5;
|
||||
cout << str5;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
A simple bounded 2-d array example.
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
using namespace std;
|
||||
|
||||
class MyArray {
|
||||
int isize, jsize;
|
||||
int *p;
|
||||
public:
|
||||
MyArray(int i, int j);
|
||||
int &put(int i, int j);
|
||||
int get(int i, int j);
|
||||
};
|
||||
|
||||
MyArray::MyArray(int i, int j)
|
||||
{
|
||||
p = new int [i*j];
|
||||
if(!p) {
|
||||
cout << "Allocation error\n";
|
||||
exit(1);
|
||||
}
|
||||
isize = i;
|
||||
jsize = j;
|
||||
}
|
||||
|
||||
int &MyArray::put(int i, int j)
|
||||
{
|
||||
if(i <0 || i>=isize || j<0 || j>=jsize) {
|
||||
cout << "Bounds error!!!\n";
|
||||
exit(1);
|
||||
}
|
||||
return p[i*jsize + j];
|
||||
}
|
||||
|
||||
int MyArray::get(int i, int j)
|
||||
{
|
||||
if(i <0 || i>=isize || j<0 || j>=jsize) {
|
||||
cout << "Bounds error!!!\n";
|
||||
exit(1);
|
||||
}
|
||||
return p[i*jsize +j];
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
MyArray a(2, 3);
|
||||
int i, j;
|
||||
|
||||
for(i = 0; i <2; i++)
|
||||
for(j=0; j<3; j++)
|
||||
a.put(i, j) = i+j;
|
||||
|
||||
for(i = 0; i <2; i++)
|
||||
for(j=0; j<3; j++)
|
||||
cout << a.get(i, j) << ' ';
|
||||
|
||||
a.put(10, 10);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
A simple class called Point, with all necessary functions
|
||||
|
||||
# include<iostream.h>
|
||||
# include<conio.h>
|
||||
# include<math.h>
|
||||
|
||||
class point
|
||||
{
|
||||
int x,y,z;
|
||||
public:
|
||||
point()
|
||||
{
|
||||
x=y=z=0;
|
||||
}
|
||||
point(int i,int j,int k)
|
||||
{
|
||||
x=i;
|
||||
y=j;
|
||||
z=k;
|
||||
}
|
||||
point(point &a)
|
||||
{
|
||||
x=a.x;
|
||||
y=a.y;
|
||||
z=a.z;
|
||||
}
|
||||
|
||||
negate()
|
||||
{
|
||||
x=-x;
|
||||
y=-y;
|
||||
z=-z;
|
||||
}
|
||||
void print()
|
||||
{
|
||||
cout<<"("<<x<<","<<y<<","<<z<<")";
|
||||
}
|
||||
int norm()
|
||||
{
|
||||
return(sqrt(x*x+y*y+z*z));
|
||||
}
|
||||
};
|
||||
void main()
|
||||
{
|
||||
clrscr();
|
||||
point p(2,3,4),p1(p);
|
||||
|
||||
cout<<"The point has the coordinates ";
|
||||
p.print();
|
||||
cout<<"
|
||||
The point coordinates after negation ";
|
||||
p.negate();
|
||||
p.print();
|
||||
cout<<"
|
||||
Normal Distance of the point from (0,0,0) is "<<p.norm();
|
||||
cout<<"
|
||||
The coordinates of the point p1 after copy constructor is ";
|
||||
p1.print();
|
||||
getch();
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
A simple class with member variable, constructor, destructor
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class who {
|
||||
char name;
|
||||
public:
|
||||
who(char c) {
|
||||
name = c;
|
||||
cout << "Constructing who";
|
||||
cout << name << endl;
|
||||
}
|
||||
~who() {
|
||||
cout << "Destructing who: " << name << endl;
|
||||
}
|
||||
};
|
||||
|
||||
who makewho()
|
||||
{
|
||||
who temp('B');
|
||||
return temp;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
who ob('A');
|
||||
|
||||
makewho();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
A simple class with member variable, constructor, destructor
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class who {
|
||||
char name;
|
||||
public:
|
||||
who(char c) {
|
||||
name = c;
|
||||
cout << "Constructing who";
|
||||
cout << name << endl;
|
||||
}
|
||||
~who() {
|
||||
cout << "Destructing who: " << name << endl;
|
||||
}
|
||||
};
|
||||
|
||||
who makewho()
|
||||
{
|
||||
who temp('B');
|
||||
return temp;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
who ob('A');
|
||||
|
||||
makewho();
|
||||
|
||||
return 0;
|
||||
}
|
||||
A simple conversion function example.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class MyClass {
|
||||
int x, y;
|
||||
public:
|
||||
MyClass(int i, int j) {
|
||||
x = i;
|
||||
y = j;
|
||||
}
|
||||
operator int() {
|
||||
return x*y;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
MyClass object1(2, 3), object2(4, 3);
|
||||
int i;
|
||||
|
||||
i = object1; // automatically convert to integer
|
||||
cout << i << '\n';
|
||||
|
||||
i = 100 + object2; // convert object2 to integer
|
||||
cout << i << '\n';
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
A simple example of inheritance.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class BaseClass {
|
||||
int i;
|
||||
public:
|
||||
void setInt(int n);
|
||||
int getInt();
|
||||
};
|
||||
|
||||
class DerivedClass : public BaseClass {
|
||||
int j;
|
||||
public:
|
||||
void setJ(int n);
|
||||
int mul();
|
||||
};
|
||||
|
||||
void BaseClass::setInt(int n)
|
||||
{
|
||||
i = n;
|
||||
}
|
||||
|
||||
int BaseClass::getInt()
|
||||
{
|
||||
return i;
|
||||
}
|
||||
|
||||
void DerivedClass::setJ(int n)
|
||||
{
|
||||
j = n;
|
||||
}
|
||||
|
||||
int DerivedClass::mul()
|
||||
{
|
||||
return j * getInt();
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
DerivedClass ob;
|
||||
|
||||
ob.setInt(10); // load i in BaseClass
|
||||
ob.setJ(4); // load j in DerivedClass
|
||||
|
||||
cout << ob.mul(); // displays 40
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
A simple example using a virtual function.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class BaseClass {
|
||||
public:
|
||||
int i;
|
||||
BaseClass(int x) {
|
||||
i = x;
|
||||
}
|
||||
virtual void myFunction()
|
||||
{
|
||||
cout << "Using BaseClass version of myFunction(): ";
|
||||
cout << i << '\n';
|
||||
}
|
||||
};
|
||||
|
||||
class DerivedClass1 : public BaseClass {
|
||||
public:
|
||||
DerivedClass1(int x) : BaseClass(x) {}
|
||||
void myFunction()
|
||||
{
|
||||
cout << "Using DerivedClass1's version of myFunction(): ";
|
||||
cout << i*i << '\n';
|
||||
}
|
||||
};
|
||||
|
||||
class DerivedClass2 : public BaseClass {
|
||||
public:
|
||||
DerivedClass2(int x) : BaseClass(x) {}
|
||||
void myFunction()
|
||||
{
|
||||
cout << "Using DerivedClass2's version of myFunction(): ";
|
||||
cout << i+i << '\n';
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
BaseClass *p;
|
||||
BaseClass ob(10);
|
||||
DerivedClass1 derivedObject1(10);
|
||||
DerivedClass2 derivedObject2(10);
|
||||
|
||||
p = &ob;
|
||||
p->myFunction(); // use BaseClass's myFunction()
|
||||
|
||||
p = &derivedObject1;
|
||||
p->myFunction(); // use DerivedClass1's myFunction()
|
||||
|
||||
p = &derivedObject2;
|
||||
p->myFunction(); // use DerivedClass2's myFunction()
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
A simple generic linked list.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
template <class dataType> class list {
|
||||
dataType data;
|
||||
list *next;
|
||||
public:
|
||||
list(dataType d);
|
||||
void add(list *node) {
|
||||
node->next = this;
|
||||
next = 0;
|
||||
}
|
||||
list *getnext() {
|
||||
return next;
|
||||
}
|
||||
dataType getdata() {
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
template <class dataType> list<dataType>::list(dataType d)
|
||||
{
|
||||
data = d;
|
||||
next = 0;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
list<char> start('a');
|
||||
list<char> *p, *last;
|
||||
int i;
|
||||
|
||||
last = &start;
|
||||
for(i=1; i <26; i++) {
|
||||
p = new list<char> ('a' + i);
|
||||
p->add(last);
|
||||
last = p;
|
||||
}
|
||||
|
||||
p = &start;
|
||||
while(p) {
|
||||
cout << p->getdata();
|
||||
p = p->getnext();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
A simple map: char and int
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
map<char, int> mapObject;
|
||||
int i;
|
||||
|
||||
for(i = 0; i <26; i++) {
|
||||
mapObject.insert(pair<char, int>('A'+i, 65+i));
|
||||
}
|
||||
|
||||
char ch;
|
||||
cout << "Enter key: ";
|
||||
cin >> ch;
|
||||
|
||||
map<char, int>::iterator p;
|
||||
|
||||
p = mapObject.find(ch);
|
||||
if(p != mapObject.end())
|
||||
cout << "Its ASCII value is " << p->second;
|
||||
else
|
||||
cout << "Key not in map.\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
A simple output manipulator: sethex
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
using namespace std;
|
||||
|
||||
|
||||
ostream &sethex(ostream &stream)
|
||||
{
|
||||
stream.setf(ios::showbase);
|
||||
stream.setf(ios::hex, ios::basefield);
|
||||
|
||||
return stream;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
cout << 256 << " " << sethex << 256;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
A simple program demonstrating the use of pointers.
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
// declare an integer and a float variable
|
||||
int IntNum;
|
||||
float FloatNum;
|
||||
|
||||
// declare integer and float pointers
|
||||
int *pIntNum;
|
||||
float *pFloatNum;
|
||||
|
||||
// initialize the integer and float variables
|
||||
IntNum = 10;
|
||||
FloatNum = 12.34;
|
||||
|
||||
// store addresses in pointers
|
||||
pIntNum = &IntNum;
|
||||
pFloatNum = &FloatNum;
|
||||
|
||||
// print out the original values
|
||||
cout << "Before increment: " << endl;
|
||||
cout << "\t IntNum is: " << IntNum << endl;
|
||||
cout << "\t FloatNum is: " << FloatNum << endl;
|
||||
|
||||
// note that we need to dereference a pointer in order
|
||||
// to extract the value it contains.
|
||||
cout << "\t pIntNum contains: " << *pIntNum << endl;
|
||||
cout << "\t pFloatNum contains: " << *pFloatNum << endl;
|
||||
|
||||
// increment values of the integer and float variables
|
||||
(*pIntNum)++; // dereference and then increment
|
||||
(*pFloatNum)++;
|
||||
|
||||
// print out the values after increment
|
||||
cout << "After increment: " << endl;
|
||||
cout << "\t IntNum is: " << IntNum << endl;
|
||||
cout << "\t FloatNum is: " << FloatNum << endl;
|
||||
|
||||
cout << "\t pIntNum contains: " << *pIntNum << endl;
|
||||
cout << "\t pFloatNum contains: " << *pFloatNum << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
A simple program demonstrating the use of reference
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int Len, Wid; // declare int variables
|
||||
|
||||
// Create references to int variables.
|
||||
// Now rLen and Len are aliases to each other,
|
||||
// and rWid and Wid are also aliases to each other.
|
||||
int &rLen = Len;
|
||||
int &rWid = Wid;
|
||||
|
||||
// Initialized the two int variables
|
||||
Len = 10; // rLen is also initialized to be 10
|
||||
Wid = 20; // rWid is also initialized to be 20
|
||||
|
||||
// Printing out the values for int and int references
|
||||
cout << "Len is: " << Len << ", and Wid is: " << Wid << endl;
|
||||
cout << "rLen is: " << rLen << ", and rWid is: " << rWid << endl;
|
||||
cout << endl;
|
||||
|
||||
// Printing out the address of int and references to int
|
||||
cout << "Address of Len is: " << &Len << endl;
|
||||
cout << "Address of rLen is: " << &rLen << endl;
|
||||
if(&Len == &rLen)
|
||||
{
|
||||
cout << "Address of Len is equal to address of rLen!" << endl;
|
||||
}
|
||||
cout << "Address of Wid is: " << &Wid << endl;
|
||||
cout << "Address of rWid is: " << &rWid << endl;
|
||||
if(&Wid == &Wid)
|
||||
{
|
||||
cout << "Address of Wid is equal to address of rWid!" << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
A simple program showing inheritance
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class base {
|
||||
int i, j;
|
||||
public:
|
||||
void set(int a, int b) { i = a; j = b; }
|
||||
void show() { cout << i << " " << j << "\n"; }
|
||||
};
|
||||
|
||||
// inheritance
|
||||
class derived : public base {
|
||||
int k;
|
||||
public:
|
||||
derived(int x) { k = x; }
|
||||
void showk() { cout << k << "\n"; }
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
derived ob(3);
|
||||
|
||||
ob.set(1, 2); // access member of base
|
||||
ob.show(); // access member of base
|
||||
|
||||
ob.showk(); // uses member of derived class
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
A simple stack example: push, empty, pop and top
|
||||
#include <iostream>
|
||||
#include <stack>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
stack<char> stackObject;
|
||||
|
||||
stackObject.push('A');
|
||||
stackObject.push('B');
|
||||
stackObject.push('C');
|
||||
stackObject.push('D');
|
||||
|
||||
while(!stackObject.empty()) {
|
||||
cout << "Popping: ";
|
||||
cout << stackObject.top() << endl;
|
||||
stackObject.pop();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
A static member variable example.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class myclass {
|
||||
static int i;
|
||||
public:
|
||||
void setInt(int n) {
|
||||
i = n;
|
||||
}
|
||||
int getInt() {
|
||||
return i;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
int myclass::i; // Definition of myclass::i. i is still private to myclass.
|
||||
|
||||
int main()
|
||||
{
|
||||
myclass object1, object2;
|
||||
|
||||
object1.setInt(10);
|
||||
|
||||
cout << "object1.i: " << object1.getInt() << '\n'; // displays 10
|
||||
cout << "object2.i: " << object2.getInt() << '\n'; // also displays 10
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
A string demonstration: assignment, concatenate, compare
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
string str1("Alpha");
|
||||
string str2("Beta");
|
||||
string str3("Omega");
|
||||
string str4;
|
||||
|
||||
str4 = str1;
|
||||
cout << str1 << endl << str3 << endl;
|
||||
|
||||
|
||||
str4 = str1 + str2; // concatenate two strings
|
||||
cout << str4 << endl;
|
||||
|
||||
str4 = str1 + " to " + str3;
|
||||
cout << str4 << endl;
|
||||
|
||||
|
||||
if(str3 > str1) // compare strings
|
||||
cout << "str3 > str1\n";
|
||||
if(str3 == str1 + str2)
|
||||
cout << "str3 == str1+str2\n";
|
||||
|
||||
str1 = "This is a null-terminated string.\n";
|
||||
cout << str1;
|
||||
|
||||
// create a string object using another string object
|
||||
string str5(str1);
|
||||
cout << str5;
|
||||
|
||||
// input a string
|
||||
cout << "Enter a string: ";
|
||||
cin >> str5;
|
||||
cout << str5;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
A switch statement in action
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main(void)
|
||||
{
|
||||
char grade;
|
||||
cout << "Enter your grade: ";
|
||||
cin >> grade;
|
||||
switch (grade)
|
||||
{
|
||||
case 'A':
|
||||
cout << "Your average must be between 90 - 100"
|
||||
<< endl;
|
||||
break;
|
||||
case 'B':
|
||||
cout << "Your average must be between 80 - 89"
|
||||
<< endl;
|
||||
break;
|
||||
case 'C':
|
||||
cout << "Your average must be between 70 - 79"
|
||||
<< endl;
|
||||
break;
|
||||
case 'D':
|
||||
cout << "Your average must be between 60 - 69"
|
||||
<< endl;
|
||||
break;
|
||||
default:
|
||||
cout << "Your average must be below 60" << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
A vector may allocate more memory than it currently needs.
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<char> vectorObject(10);
|
||||
|
||||
cout << "Initial size: " << vectorObject.size() << endl;
|
||||
cout << "Initial capacity: " << vectorObject.capacity();
|
||||
cout << "\n\n";
|
||||
|
||||
vectorObject.push_back('X');
|
||||
|
||||
cout << "Size after push_back: " << vectorObject.size() << endl;
|
||||
cout << "New capacity: " << vectorObject.capacity();
|
||||
cout << "\n\n";
|
||||
|
||||
vectorObject.resize(100);
|
||||
|
||||
cout << "Size after resize: " << vectorObject.size() << endl;
|
||||
cout << "Capacity after resize: " << vectorObject.capacity();
|
||||
cout << "\n\n";
|
||||
|
||||
vectorObject.push_back('Y');
|
||||
|
||||
cout << "Size after push_back: " << vectorObject.size() << endl;
|
||||
cout << "New capacity: " << vectorObject.capacity();
|
||||
cout << "\n\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
A while Loop - Generate a random number between 0 and 9
|
||||
and let the user guess it.
|
||||
Use a while loop. Exit when user guessed right.
|
||||
|
||||
#include <iostream>
|
||||
// <cstdlib> is needed in order to use the rand().
|
||||
// For older compilers, use <stdlib.h>
|
||||
#include <stdlib.h>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int magic; // magic number
|
||||
int guess; // user's guess
|
||||
|
||||
cout << "I will come up with a magic number between 0 and 9 ";
|
||||
cout << "and ask you to guess it." << endl;
|
||||
|
||||
magic = rand()%10; // get a random number between 0 and 9
|
||||
|
||||
cout << "Enter your guess: ";
|
||||
cin >> guess;
|
||||
|
||||
while (guess != magic) // as long as guess is incorrect
|
||||
{
|
||||
if(guess > magic)
|
||||
{
|
||||
cout << "Too big! Guess again..." << endl;
|
||||
}
|
||||
else // guess is less than magic
|
||||
{
|
||||
cout << "Too small! Guess again..." << endl;
|
||||
}
|
||||
cin >> guess;
|
||||
}
|
||||
cout << "You are RIGHT!" << endl;;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
Absolute Value Calculation
|
||||
This is a simple function that calculates the absolute value of a number:
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
double Abs(double Nbr)
|
||||
{
|
||||
// return (Nbr >= 0) ? Nbr : -Nbr;
|
||||
if( Nbr >= 0 )
|
||||
return Nbr;
|
||||
else
|
||||
return -Nbr;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
double Number = -88;
|
||||
double Nbr = Abs(Number);
|
||||
|
||||
cout << "The absolute value of " << Number << " is " << Nbr << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Here is an example of running the program:
|
||||
|
||||
The absolute value of -88 is 88
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
Abstract base class
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class CPolygon {
|
||||
protected:
|
||||
int width, height;
|
||||
public:
|
||||
void set_values (int a, int b)
|
||||
{ width=a; height=b; }
|
||||
virtual int area (void) =0;
|
||||
};
|
||||
|
||||
class CRectangle: public CPolygon {
|
||||
public:
|
||||
int area (void)
|
||||
{ return (width * height); }
|
||||
};
|
||||
|
||||
class CTriangle: public CPolygon {
|
||||
public:
|
||||
int area (void)
|
||||
{ return (width * height / 2); }
|
||||
};
|
||||
|
||||
int main () {
|
||||
CRectangle rect;
|
||||
CTriangle trgl;
|
||||
CPolygon * ppoly1 = ▭
|
||||
CPolygon * ppoly2 = &trgl;
|
||||
ppoly1->set_values (4,5);
|
||||
ppoly2->set_values (4,5);
|
||||
cout << ppoly1->area() << endl;
|
||||
cout << ppoly2->area() << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
Abstract classes by virtual function with no body
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class Animal{
|
||||
public:
|
||||
Animal(int health = 100);
|
||||
virtual void Greet() const = 0; //pure virtual member function
|
||||
virtual void DisplayHealth() const;
|
||||
|
||||
protected:
|
||||
int m_Health;
|
||||
};
|
||||
|
||||
Animal::Animal(int health): m_Health(health){}
|
||||
void Animal::DisplayHealth() const{
|
||||
cout << "Health: " << m_Health << endl;
|
||||
}
|
||||
|
||||
class Orc : public Animal{
|
||||
public:
|
||||
Orc(int health = 120);
|
||||
virtual void Greet() const;
|
||||
};
|
||||
|
||||
Orc::Orc(int health):
|
||||
Animal(health)
|
||||
{}
|
||||
|
||||
void Orc::Greet() const
|
||||
{
|
||||
cout << "The orc grunts hello.\n";
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
Animal* pAnimal = new Orc();
|
||||
pAnimal->Greet();
|
||||
pAnimal->DisplayHealth();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
Access a vector using an iterator.
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<int> v;
|
||||
int i;
|
||||
|
||||
for(i = 0; i <10; i++)
|
||||
v.push_back(i);
|
||||
|
||||
for(i = 0; i <10; i++)
|
||||
cout << v[ i ] << " ";
|
||||
cout << endl;
|
||||
|
||||
vector<int>::iterator p = v.begin();
|
||||
while(p != v.end()) {
|
||||
cout << *p << " ";
|
||||
p++;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
Access control under inheritance
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class Enemy
|
||||
{
|
||||
public:
|
||||
Enemy(): m_Damage(10) {}
|
||||
|
||||
void Attack() const
|
||||
{ cout << "Attack inflicts " << m_Damage << " damage points!\n"; }
|
||||
|
||||
protected:
|
||||
int m_Damage;
|
||||
};
|
||||
|
||||
class Boss : public Enemy
|
||||
{
|
||||
public:
|
||||
Boss(): m_DamageMultiplier(3) {}
|
||||
|
||||
void SpecialAttack() const
|
||||
{ cout << "Special Attack inflicts " << (m_DamageMultiplier * m_Damage);
|
||||
cout << " damage points!\n"; }
|
||||
|
||||
private:
|
||||
int m_DamageMultiplier;
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
Enemy enemy1;
|
||||
enemy1.Attack();
|
||||
|
||||
Boss boss1;
|
||||
boss1.Attack();
|
||||
boss1.SpecialAttack();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Access out-of-range element
|
||||
#include <iostream>
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
|
||||
#include <vector> // vector class-template definition
|
||||
#include <algorithm> // copy algorithm
|
||||
#include <iterator> // ostream_iterator iterator
|
||||
#include <stdexcept> // out_of_range exception
|
||||
|
||||
int main()
|
||||
{
|
||||
int array[ 6 ] = { 1, 2, 3, 4, 5, 6 };
|
||||
std::vector< int > integers( array, array + 6 );
|
||||
std::ostream_iterator< int > output( cout, " " );
|
||||
|
||||
integers.push_back( 2 );
|
||||
integers.push_back( 3 );
|
||||
integers.push_back( 4 );
|
||||
|
||||
cout << "Vector integers contains: ";
|
||||
std::copy( integers.begin(), integers.end(), output );
|
||||
|
||||
try
|
||||
{
|
||||
integers.at( 100 ) = 777;
|
||||
} catch ( std::out_of_range outOfRange ) // out_of_range exception
|
||||
{
|
||||
cout << "\n\nException: " << outOfRange.what();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
Vector integers contains: 1 2 3 4 5 6 2 3 4
|
||||
|
||||
Exception: vector::_M_range_check
|
||||
*/
|
||||
@@ -0,0 +1,45 @@
|
||||
Access the elements of a vector through an iterator.
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<int> vectorObject(10);
|
||||
vector<int>::iterator p;
|
||||
int i;
|
||||
|
||||
p = vectorObject.begin();
|
||||
i = 0;
|
||||
while(p != vectorObject.end()) {
|
||||
*p = i;
|
||||
p++;
|
||||
i++;
|
||||
}
|
||||
|
||||
|
||||
cout << "Original contents:\n";
|
||||
p = vectorObject.begin();
|
||||
while(p != vectorObject.end()) {
|
||||
cout << *p << " ";
|
||||
p++;
|
||||
}
|
||||
cout << "\n\n";
|
||||
|
||||
|
||||
p = vectorObject.begin();
|
||||
while(p != vectorObject.end()) {
|
||||
*p = *p * 2; // change contents of vector
|
||||
p++;
|
||||
}
|
||||
|
||||
cout << "Modified Contents:\n";
|
||||
p = vectorObject.begin();
|
||||
while(p != vectorObject.end()) {
|
||||
cout << *p << " "; // display contents of vector
|
||||
p++;
|
||||
}
|
||||
cout << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
Accessing Character Elements of an STL String
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
int main(){
|
||||
using namespace std;
|
||||
|
||||
string str ("Hello String");
|
||||
|
||||
for(size_t i = 0; i < str.length(); ++ i){
|
||||
cout << "Character [" << i << "] is: ";
|
||||
cout << str [i] << endl;
|
||||
}
|
||||
cout << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
Accessing Characters In Strings
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cctype>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
string text;
|
||||
|
||||
cout << "Counts words. Enter a text and terminate with a period and return:\n";
|
||||
|
||||
getline( cin, text, '.'); // Reads a text up to the first '.'
|
||||
|
||||
int i, // Index
|
||||
|
||||
numberOfWhiteSpace = 0, // Number of white spaces
|
||||
|
||||
numberOfWords = 0; // Number of words
|
||||
|
||||
bool fSpace = true; // Flag for white space
|
||||
for( i = 0; i < text.length(); ++i)
|
||||
{
|
||||
if( isspace( text[i]) ) // white space?
|
||||
{
|
||||
++numberOfWhiteSpace;
|
||||
fSpace = true;
|
||||
}
|
||||
else if( fSpace) // At the beginning of a word?
|
||||
{
|
||||
++numberOfWords;
|
||||
fSpace = false;
|
||||
}
|
||||
}
|
||||
cout << "\nYour text contains (without periods)"
|
||||
<< "\ncharacters: " << text.length()
|
||||
<< "\nwords: " << numberOfWords
|
||||
<< "\nwhite spaces: " << numberOfWhiteSpace
|
||||
<< endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
Accessing Data in a File
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
template <class T>
|
||||
void print(T& c){
|
||||
for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
|
||||
std::cout << *i << endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main(){
|
||||
vector<int> output_data( 10 );
|
||||
generate( output_data.begin(), output_data.end(), rand );
|
||||
|
||||
transform( output_data.begin(), output_data.end(),output_data.begin(), bind2nd( modulus<int>(), 10 ) );
|
||||
|
||||
ofstream out( "data.txt" );
|
||||
if( !out )
|
||||
{
|
||||
cout << "Couldn't open output file\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
copy( output_data.begin(), output_data.end(),ostream_iterator<int>( out, "\n" ) );
|
||||
out.close();
|
||||
|
||||
ifstream in( "data.txt" );
|
||||
if( !in )
|
||||
{
|
||||
cout << "Couldn't open input file\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
vector<int> input_data( (istream_iterator<int>( in )),istream_iterator<int>() );
|
||||
in.close();
|
||||
|
||||
print( output_data );
|
||||
print( input_data );
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
Accessing Private Data Members in C++. This is a flaw in the language
|
||||
|
||||
#include <iostream.h>
|
||||
#include <string.h>
|
||||
#include <conio.h>
|
||||
|
||||
class bestcoder
|
||||
{
|
||||
private:
|
||||
|
||||
char name[40];
|
||||
char grade;
|
||||
int age;
|
||||
|
||||
public:
|
||||
|
||||
bestcoder(char* nam="Some Dude",char gr='A',int saal=25)
|
||||
{
|
||||
strcpy(name,nam);
|
||||
grade=gr;
|
||||
age=saal;
|
||||
}
|
||||
|
||||
friend ostream& operator <<(ostream& s,bestcoder b);
|
||||
};
|
||||
|
||||
ostream& operator <<(ostream& s,bestcoder b)
|
||||
{
|
||||
s<<"Best Coder :"<<b.name<<endl
|
||||
<<"His Rating :"<<b.grade<<endl
|
||||
<<"Current Age :"<<b.age<<"
|
||||
|
||||
";
|
||||
return s;
|
||||
}
|
||||
|
||||
struct hackit
|
||||
{
|
||||
char name[40];
|
||||
char grade;
|
||||
char age;
|
||||
};
|
||||
|
||||
void main()
|
||||
{
|
||||
bestcoder bc;
|
||||
cout<<bc;
|
||||
void* ptr=&bc;
|
||||
struct hackit* bettercoder=(hackit*)ptr;
|
||||
bettercoder->grade='F';
|
||||
bettercoder->age=56;
|
||||
cout<<bc;
|
||||
strcpy(bettercoder->name,"xxx");
|
||||
bettercoder->age=14;
|
||||
bettercoder->grade='A';
|
||||
cout<<bc;
|
||||
getch();
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
Accessing SQL Server from C++
|
||||
|
||||
#define DBNTWIN32
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
#include <sqlfront.h>
|
||||
#include <sqldb.h>
|
||||
|
||||
// Forward declarations of the error handler and message handler.
|
||||
|
||||
int err_handler(PDBPROCESS, INT, INT, INT, LPCSTR, LPCSTR);
|
||||
int msg_handler(PDBPROCESS, DBINT, INT, INT, LPCSTR, LPCSTR,
|
||||
LPCSTR, DBUSMALLINT);
|
||||
main()
|
||||
{
|
||||
PDBPROCESS dbproc; // The connection with SQL Server.
|
||||
PLOGINREC login; // The login information.
|
||||
DBCHAR name[100];
|
||||
DBCHAR city[100];
|
||||
|
||||
// Install user-supplied error- and message-handling functions.
|
||||
|
||||
dberrhandle (err_handler);
|
||||
dbmsghandle (msg_handler);
|
||||
|
||||
// Initialize DB-Library.
|
||||
|
||||
dbinit ();
|
||||
|
||||
// Get a LOGINREC.
|
||||
|
||||
login = dblogin ();
|
||||
DBSETLUSER (login, "my_login");
|
||||
DBSETLPWD (login, "my_password");
|
||||
DBSETLAPP (login, "example");
|
||||
|
||||
// Get a DBPROCESS structure for communication with SQL Server.
|
||||
|
||||
dbproc = dbopen (login, "my_server");
|
||||
|
||||
// Retrieve some columns from the authors table in the
|
||||
// pubs database.
|
||||
// First, put the command into the command buffer.
|
||||
|
||||
dbcmd (dbproc, "SELECT au_lname, city FROM pubs..authors");
|
||||
dbcmd (dbproc, " WHERE state = 'CA' ");
|
||||
|
||||
// Send the command to SQL Server and start execution.
|
||||
|
||||
dbsqlexec (dbproc);
|
||||
|
||||
// Process the results.
|
||||
|
||||
if (dbresults (dbproc) == SUCCEED)
|
||||
{
|
||||
|
||||
// Bind column to program variables.
|
||||
|
||||
dbbind (dbproc, 1, NTBSTRINGBIND, 0, name);
|
||||
dbbind (dbproc, 2, NTBSTRINGBIND, 0, city);
|
||||
|
||||
// Retrieve and print the result rows.
|
||||
|
||||
while (dbnextrow (dbproc) != NO_MORE_ROWS)
|
||||
{
|
||||
printf ("%s from %s\n", name, city);
|
||||
}
|
||||
}
|
||||
|
||||
// Close the connection to SQL Server.
|
||||
|
||||
dbexit ();
|
||||
return (0);
|
||||
}
|
||||
|
||||
int err_handler (PDBPROCESS dbproc, INT severity,
|
||||
INT dberr, INT oserr, LPCSTR dberrstr, LPCSTR oserrstr)
|
||||
{
|
||||
printf ("DB-Library Error %i: %s\n", dberr, dberrstr);
|
||||
if (oserr != DBNOERR)
|
||||
{
|
||||
printf ("Operating System Error %i: %s\n", oserr, oserrstr);
|
||||
}
|
||||
return (INT_CANCEL);
|
||||
}
|
||||
|
||||
int msg_handler (PDBPROCESS dbproc, DBINT msgno, INT msgstate,
|
||||
INT severity, LPCSTR msgtext, LPCSTR server,
|
||||
LPCSTR procedure, DBUSMALLINT line)
|
||||
{
|
||||
printf ("SQL Server Message %ld: %s\n", msgno, msgtext);
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
Accessing a Vector Through an Iterator
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <cctype>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
vector<char> vectorObject(10);
|
||||
vector<char>::iterator p; // create an iterator
|
||||
int i;
|
||||
|
||||
|
||||
p = vectorObject.begin();
|
||||
i = 0;
|
||||
while(p != vectorObject.end()) {
|
||||
*p = i + 'a';
|
||||
p++;
|
||||
i++;
|
||||
}
|
||||
|
||||
cout << "Original contents:\n";
|
||||
p = vectorObject.begin();
|
||||
while(p != vectorObject.end()) {
|
||||
cout << *p << " ";
|
||||
p++;
|
||||
}
|
||||
cout << "\n\n";
|
||||
// change contents of vector
|
||||
p = vectorObject.begin();
|
||||
while(p != vectorObject.end()) {
|
||||
*p = toupper(*p);
|
||||
p++;
|
||||
}
|
||||
// display contents of vector
|
||||
cout << "Modified Contents:\n";
|
||||
p = vectorObject.begin();
|
||||
while(p != vectorObject.end()) {
|
||||
cout << *p << " ";
|
||||
p++;
|
||||
}
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
Accessing static members without an object.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
class Cat
|
||||
{
|
||||
public:
|
||||
Cat(int age):itsAge(age){count++; }
|
||||
virtual ~Cat() { count--; }
|
||||
virtual int GetAge() { return itsAge; }
|
||||
virtual void SetAge(int age) { itsAge = age; }
|
||||
static int count;
|
||||
|
||||
private:
|
||||
int itsAge;
|
||||
|
||||
};
|
||||
|
||||
int Cat::count = 0;
|
||||
|
||||
void TelepathicFunction();
|
||||
|
||||
int main()
|
||||
{
|
||||
const int MaxCats = 5; int i;
|
||||
Cat *CatHouse[MaxCats];
|
||||
for (i = 0; i<MaxCats; i++)
|
||||
{
|
||||
CatHouse[i] = new Cat(i);
|
||||
TelepathicFunction();
|
||||
}
|
||||
|
||||
for ( i = 0; i<MaxCats; i++)
|
||||
{
|
||||
delete CatHouse[i];
|
||||
TelepathicFunction();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void TelepathicFunction()
|
||||
{
|
||||
cout << "There are ";
|
||||
cout << Cat::count << " cats alive!\n";
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
Accumulate value in a vector
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
double arithmeticMean(const vector<int>& nums)
|
||||
{
|
||||
double sum = accumulate(nums.begin(), nums.end(), 0);
|
||||
return (sum / nums.size());
|
||||
}
|
||||
|
||||
int product(int num1, int num2)
|
||||
{
|
||||
return (num1 * num2);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
vector<int> myVector;
|
||||
|
||||
myVector.push_back(1);
|
||||
myVector.push_back(2);
|
||||
myVector.push_back(3);
|
||||
myVector.push_back(4);
|
||||
|
||||
cout << "The arithmetic mean is " << arithmeticMean(myVector) << endl;
|
||||
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
Add a friend extractor for objects of type MyClass.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class MyClass {
|
||||
int x, y;
|
||||
public:
|
||||
MyClass() {
|
||||
x = 0;
|
||||
y = 0;
|
||||
}
|
||||
MyClass(int i, int j) {
|
||||
x = i;
|
||||
y = j;
|
||||
}
|
||||
friend ostream &operator<<(ostream &stream, MyClass ob);
|
||||
friend istream &operator>>(istream &stream, MyClass &ob);
|
||||
};
|
||||
|
||||
ostream &operator<<(ostream &stream, MyClass ob)
|
||||
{
|
||||
stream << ob.x << ", " << ob.y << '\n';
|
||||
return stream;
|
||||
}
|
||||
|
||||
istream &operator>>(istream &stream, MyClass &ob)
|
||||
{
|
||||
cout << "Enter MyClassinates: ";
|
||||
stream >> ob.x >> ob.y;
|
||||
return stream;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
MyClass a(1, 1), b(10, 23);
|
||||
|
||||
cout << a << b;
|
||||
|
||||
cin >> a;
|
||||
cout << a;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
Add an else part to the if statement
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main(void)
|
||||
{
|
||||
int num;
|
||||
cout << "Enter a whole number: ";
|
||||
cin >> num;
|
||||
if ( num % 2 == 0 )
|
||||
cout << "The number is even" << endl;
|
||||
else
|
||||
cout << "The number is odd" << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
|
||||
|
||||
Add elements in a list to a set
|
||||
#include <iostream>
|
||||
#include <cassert>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <set>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
string s("There is no distinctly native American criminal class");
|
||||
|
||||
|
||||
list<char> list1(s.begin(), s.end());
|
||||
|
||||
// Put the characters in list1 into set1:
|
||||
set<char> set1;
|
||||
list<char>::iterator i;
|
||||
|
||||
for (i = list1.begin(); i != list1.end(); ++i)
|
||||
set1.insert(*i);
|
||||
|
||||
set<char>::iterator j;
|
||||
|
||||
for (j = set1.begin(); j != set1.end(); ++j)
|
||||
cout << *j;
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
ATacdehilmnorstvy
|
||||
*/
|
||||
@@ -0,0 +1,36 @@
|
||||
Add elements in a multiset to a list
|
||||
#include <iostream>
|
||||
#include <cassert>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <set>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
string s("There is no distinctly native American criminal class");
|
||||
|
||||
list<char> list1(s.begin(), s.end());
|
||||
|
||||
// Put the characters in list1 into multiset1:
|
||||
multiset<char> multiset1;
|
||||
list<char>::iterator i;
|
||||
for (i = list1.begin(); i != list1.end(); ++i)
|
||||
multiset1.insert(*i);
|
||||
|
||||
// Put the characters in multiset1 into list2:
|
||||
list<char> list2;
|
||||
multiset<char>::iterator k;
|
||||
for (k = multiset1.begin(); k != multiset1.end(); ++k)
|
||||
list2.push_back(*k);
|
||||
|
||||
|
||||
for (i = list2.begin(); i != list2.end(); ++i)
|
||||
cout << *i;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
ATaaaaccccdeeeehiiiiiiilllmmnnnnnorrrsssstttvy"
|
||||
*/
|
||||
@@ -0,0 +1,39 @@
|
||||
Add elements in a set to a list
|
||||
#include <iostream>
|
||||
#include <cassert>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <set>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
string s("There is no distinctly native American criminal class");
|
||||
|
||||
|
||||
list<char> list1(s.begin(), s.end());
|
||||
|
||||
// Put the characters in list1 into set1:
|
||||
set<char> set1;
|
||||
list<char>::iterator i;
|
||||
|
||||
for (i = list1.begin(); i != list1.end(); ++i)
|
||||
set1.insert(*i);
|
||||
|
||||
set<char>::iterator j;
|
||||
|
||||
list<char> list2;
|
||||
set<char>::iterator k;
|
||||
for (k = set1.begin(); k != set1.end(); ++k)
|
||||
list2.push_back(*k);
|
||||
|
||||
|
||||
for (i = list2.begin(); i != list2.end(); ++i)
|
||||
cout << *i;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
ATacdehilmnorstvy
|
||||
*/
|
||||
@@ -0,0 +1,11 @@
|
||||
Adding Strings
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
int main(void)
|
||||
{
|
||||
string firstName = "gggg";
|
||||
string lastName = "uuuut";
|
||||
cout << "Your name is " << firstName + lastName;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
Addition operator in cout
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main(void)
|
||||
{
|
||||
int total, added, dropped;
|
||||
cout << "Enter total: ";
|
||||
cin >> total;
|
||||
cout << "Enter added: ";
|
||||
cin >> added;
|
||||
total = total + added;
|
||||
cout << "Enter dropped ";
|
||||
cin >> dropped;
|
||||
total -= dropped;
|
||||
cout << "Number: " << total << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
Additional meanings for the + and = operations
|
||||
#include <iostream>
|
||||
#include <string.h>
|
||||
using namespace std;
|
||||
class str_type {
|
||||
char string[80];
|
||||
public:
|
||||
str_type(char *str = "\0") { strcpy(string, str); }
|
||||
|
||||
str_type operator+(str_type str);
|
||||
str_type operator+(char *str);
|
||||
|
||||
str_type operator=(str_type str);
|
||||
str_type operator=(char *str);
|
||||
|
||||
void show_str(void) { cout << string; }
|
||||
} ;
|
||||
|
||||
str_type str_type::operator+(str_type str) {
|
||||
str_type temp;
|
||||
|
||||
strcpy(temp.string, string);
|
||||
strcat(temp.string, str.string);
|
||||
return temp;
|
||||
}
|
||||
|
||||
str_type str_type::operator=(str_type str) {
|
||||
strcpy(string, str.string);
|
||||
return *this;
|
||||
}
|
||||
|
||||
str_type str_type::operator=(char *str)
|
||||
{
|
||||
str_type temp;
|
||||
|
||||
strcpy(string, str);
|
||||
strcpy(temp.string, string);
|
||||
return temp;
|
||||
}
|
||||
|
||||
str_type str_type::operator+(char *str)
|
||||
{
|
||||
str_type temp;
|
||||
|
||||
strcpy(temp.string, string);
|
||||
strcat(temp.string, str);
|
||||
return temp;
|
||||
}
|
||||
|
||||
main(void)
|
||||
{
|
||||
str_type a("Hello "), b("There"), c;
|
||||
|
||||
c = a + b;
|
||||
|
||||
c.show_str();
|
||||
cout << "\n";
|
||||
|
||||
a = "to program in because";
|
||||
a.show_str();
|
||||
cout << "\n";
|
||||
|
||||
b = c = "C++ is fun";
|
||||
|
||||
c = c+" "+a+" "+b;
|
||||
c.show_str();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
Address class: class definition and implementation
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
using namespace std;
|
||||
|
||||
class Address {
|
||||
char name[40];
|
||||
char street[40];
|
||||
char city[30];
|
||||
char state[3];
|
||||
char zip[10];
|
||||
public:
|
||||
void store(char *n, char *s, char *c, char *t, char *z);
|
||||
void display();
|
||||
};
|
||||
|
||||
void Address::store(char *n, char *s, char *c, char *t, char *z)
|
||||
{
|
||||
strcpy(name, n);
|
||||
strcpy(street, s);
|
||||
strcpy(city, c);
|
||||
strcpy(state, t);
|
||||
strcpy(zip, z);
|
||||
}
|
||||
|
||||
void Address::display()
|
||||
{
|
||||
cout << name << endl;
|
||||
cout << street << endl;
|
||||
cout << city << endl;
|
||||
cout << state << endl;
|
||||
cout << zip << endl;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
Address a;
|
||||
|
||||
a.store("C", "11 Lane", "W", "In", "4");
|
||||
|
||||
a.display();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
An Array of Pointers to Class
|
||||
This program is an example of using an array of pointers to a class.
|
||||
After declaring the array, you can allocate memory for each element using the new operator.
|
||||
To access a member variable or a method of an element, you can use the -> operator:
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class CSquare
|
||||
{
|
||||
public:
|
||||
double Side;
|
||||
|
||||
CSquare() : Side(0.00) {}
|
||||
CSquare(double side) : Side(side) { }
|
||||
~CSquare() { }
|
||||
|
||||
double getSide() const { return Side; }
|
||||
void setSide(const double s)
|
||||
{
|
||||
if( s <= 0 )
|
||||
Side = 0.00;
|
||||
else
|
||||
Side = s;
|
||||
}
|
||||
|
||||
double Perimeter() { return Side * 4; }
|
||||
double Area() { return Side * Side; }
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
CSquare *sqr[4];
|
||||
|
||||
sqr[0] = new CSquare;
|
||||
sqr[0]->setSide(24.55);
|
||||
sqr[1] = new CSquare;
|
||||
sqr[1]->setSide(15.08);
|
||||
sqr[2] = new CSquare;
|
||||
sqr[2]->setSide(8.212);
|
||||
sqr[3] = new CSquare;
|
||||
sqr[3]->setSide(202.24);
|
||||
|
||||
cout << "Squares Characteristics" << endl;
|
||||
cout << "Square 1" << endl;
|
||||
cout << "Side: " << sqr[0]->getSide() << endl;
|
||||
cout << "Perimeter: " << sqr[0]->Perimeter() << endl;
|
||||
cout << "Area: " << sqr[0]->Area() << endl;
|
||||
|
||||
cout << "Square 2" << endl;
|
||||
cout << "Side: " << sqr[1]->getSide() << endl;
|
||||
cout << "Perimeter: " << sqr[1]->Perimeter() << endl;
|
||||
cout << "Area: " << sqr[1]->Area() << endl;
|
||||
|
||||
cout << "Square 3" << endl;
|
||||
cout << "Side: " << sqr[2]->getSide() << endl;
|
||||
cout << "Perimeter: " << sqr[2]->Perimeter() << endl;
|
||||
cout << "Area: " << sqr[2]->Area() << endl;
|
||||
|
||||
cout << "Square 4" << endl;
|
||||
cout << "Side: " << sqr[3]->getSide() << endl;
|
||||
cout << "Perimeter: " << sqr[3]->Perimeter() << endl;
|
||||
cout << "Area: " << sqr[3]->Area() << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
An Example of Exception Handling
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
unsigned int TypeOfLoan = 0;
|
||||
const char *LoanType[] = { "Personal",
|
||||
"Car",
|
||||
"Furniture",
|
||||
"Musical Instrument",
|
||||
"Boat" };
|
||||
|
||||
try {
|
||||
cout << "Enter the type of loan\n";
|
||||
for(int i = 0; i < 4; i++)
|
||||
cout << i + 1 << ") " << LoanType[i] << endl;
|
||||
cout << "Your choice: ";
|
||||
cin >> TypeOfLoan;
|
||||
|
||||
if( TypeOfLoan < 1 || TypeOfLoan > 5 )
|
||||
throw "Number out of range\n";
|
||||
|
||||
cout << "\nType of Loan: " << LoanType[TypeOfLoan] << endl;
|
||||
}
|
||||
catch(const char* Msg)
|
||||
{
|
||||
cout << "Error: " << Msg << endl;
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
cout << "\nSomething went wrong\n\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
An Example with Two Generic Data Types
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
template <class Type1, class Type2> class myclass
|
||||
{
|
||||
Type1 i;
|
||||
Type2 j;
|
||||
public:
|
||||
myclass(Type1 a, Type2 b) { i = a; j = b; }
|
||||
void show() { cout << i << ' ' << j << '\n'; }
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
myclass<int, double> ob1(10, 0.23);
|
||||
myclass<char, char *> ob2('X', "Templates add power.");
|
||||
|
||||
ob1.show();
|
||||
ob2.show();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
An array-based output stream
|
||||
#include <strstream>
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
char str[80];
|
||||
ostrstream outs(str, sizeof(str));
|
||||
outs << "array-based I/O. ";
|
||||
outs << 1024 << hex << " ";
|
||||
outs.setf(ios::showbase);
|
||||
outs << 100 << ' ' << 99.789 << ends;
|
||||
cout << str;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
An example that uses typeid for base and derived classes
|
||||
#include <iostream>
|
||||
#include <typeinfo>
|
||||
using namespace std;
|
||||
|
||||
class BaseClass {
|
||||
virtual void f() {}; // make BaseClass polymorphic
|
||||
|
||||
};
|
||||
|
||||
class Derived1: public BaseClass {
|
||||
|
||||
};
|
||||
|
||||
class Derived2: public BaseClass {
|
||||
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
int i;
|
||||
BaseClass *p, baseob;
|
||||
Derived1 object1;
|
||||
Derived2 object2;
|
||||
|
||||
cout << "Typeid of i is ";
|
||||
cout << typeid(i).name() << endl;
|
||||
|
||||
p = &baseob;
|
||||
cout << "p is pointing to an object of type ";
|
||||
cout << typeid(*p).name() << endl;
|
||||
|
||||
p = &object1;
|
||||
cout << "p is pointing to an object of type ";
|
||||
cout << typeid(*p).name() << endl;
|
||||
|
||||
p = &object2;
|
||||
cout << "p is pointing to an object of type ";
|
||||
cout << typeid(*p).name() << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
An example that uses typeid on a polymorphic class hierarchy
|
||||
#include <iostream>
|
||||
#include <typeinfo>
|
||||
using namespace std;
|
||||
class Mammal {
|
||||
public:
|
||||
virtual bool laysEggs() {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
class Cat: public Mammal {
|
||||
public:
|
||||
};
|
||||
class Platypus: public Mammal {
|
||||
public:
|
||||
bool laysEggs() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
int main()
|
||||
{
|
||||
Mammal *p, AnyMammal;
|
||||
Cat cat;
|
||||
Platypus platypus;
|
||||
p = &AnyMammal;
|
||||
cout << "p is pointing to an object of type ";
|
||||
cout << typeid(*p).name() << endl;
|
||||
p = &cat;
|
||||
cout << "p is pointing to an object of type ";
|
||||
cout << typeid(*p).name() << endl;
|
||||
p = &platypus;
|
||||
cout << "p is pointing to an object of type ";
|
||||
cout << typeid(*p).name() << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
An exception can be thrown from outside the try block
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
void myFunction(int test)
|
||||
{
|
||||
cout << "Inside myFunction, test is: " << test << "\n";
|
||||
if(test) throw test;
|
||||
}
|
||||
int main()
|
||||
{
|
||||
cout << "Start\n";
|
||||
try {
|
||||
cout << "Inside try block\n";
|
||||
myFunction(0);
|
||||
myFunction(1);
|
||||
myFunction(2);
|
||||
}
|
||||
catch (int i) {
|
||||
cout << "Caught an exception -- value is: ";
|
||||
cout << i << "\n";
|
||||
}
|
||||
cout << "End";
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
An implementation of Stack data structure
|
||||
|
||||
#include <iostream>
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
using namespace std;
|
||||
|
||||
#if !defined __STACK_H
|
||||
#define __STACK_H
|
||||
|
||||
namespace stk{
|
||||
class Stack{
|
||||
private:
|
||||
int *p;
|
||||
int top,length;
|
||||
|
||||
string str()const;
|
||||
public:
|
||||
Stack();
|
||||
Stack(const int);
|
||||
Stack(const Stack&);
|
||||
~Stack();
|
||||
|
||||
void push(int);
|
||||
int pop();
|
||||
int get_length()const;
|
||||
bool is_empty()const;
|
||||
Stack operator=(const Stack&);
|
||||
friend ostream& operator<<(ostream&,Stack&);
|
||||
|
||||
class StackException{
|
||||
private:
|
||||
string desc;
|
||||
public:
|
||||
StackException(string exp){ desc="Exception : "+exp; }
|
||||
string get_exp(){ return desc; }
|
||||
};
|
||||
};
|
||||
|
||||
Stack::Stack(){
|
||||
top=-1;
|
||||
length=0;
|
||||
p=0;
|
||||
}
|
||||
|
||||
Stack::Stack(const int size){
|
||||
top=-1;
|
||||
length=size;
|
||||
try{
|
||||
p=new int[length];
|
||||
}catch(bad_alloc ba){
|
||||
cout<<"Memory can not be alllocated
|
||||
";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Stack::Stack(const Stack &o){
|
||||
top=o.top;
|
||||
length=o.length;
|
||||
try{
|
||||
p=new int[length];
|
||||
}catch(bad_alloc ba){
|
||||
cout<<"Memory allocation failed
|
||||
";
|
||||
return;
|
||||
}
|
||||
for(int i=0;i<length;i++)
|
||||
p[i]=o.p[i];
|
||||
}
|
||||
|
||||
Stack::~Stack(){
|
||||
if(p!=0)
|
||||
delete [] p;
|
||||
}
|
||||
|
||||
void Stack::push(int elem){
|
||||
if(p==0){
|
||||
try{
|
||||
p=new int[1];
|
||||
}catch(bad_alloc ba){
|
||||
throw StackException("Memory fault
|
||||
");
|
||||
}
|
||||
length++;
|
||||
top++;
|
||||
p[top]=elem;
|
||||
}
|
||||
else if(top==(length-1)){
|
||||
int *q;
|
||||
try{
|
||||
q=new int[length+1];
|
||||
}catch(bad_alloc ba1){
|
||||
throw StackException("Memory fault
|
||||
");
|
||||
}
|
||||
for(int i=0;i<length;i++)
|
||||
q[i]=p[i];
|
||||
length++;
|
||||
top++;
|
||||
q[top]=elem;
|
||||
delete [] p;
|
||||
p=q;
|
||||
}
|
||||
else{
|
||||
top++;
|
||||
p[top]=elem;
|
||||
}
|
||||
}
|
||||
|
||||
int Stack::pop(){
|
||||
if(p==0 || top==-1){
|
||||
throw StackException("Stack empty!
|
||||
");
|
||||
}
|
||||
int ret=p[top];
|
||||
top--;
|
||||
length--;
|
||||
|
||||
if(top==-1){
|
||||
delete [] p;
|
||||
p=0;
|
||||
}
|
||||
else{
|
||||
int *q;
|
||||
try{
|
||||
q=new int[length];
|
||||
}catch(bad_alloc ba){
|
||||
throw StackException("Memory fault
|
||||
");
|
||||
}
|
||||
for(int i=0;i<length;i++)
|
||||
q[i]=p[i];
|
||||
delete [] p;
|
||||
p=q;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
int Stack::get_length()const{
|
||||
return length;
|
||||
}
|
||||
|
||||
bool Stack::is_empty()const{
|
||||
return ((p==0)? true : false);
|
||||
}
|
||||
|
||||
string Stack::str()const{ // private member function
|
||||
stringstream ss;
|
||||
for(int i=0;i<length;i++){
|
||||
ss << p[i];
|
||||
if(i!=(length-1))
|
||||
ss << ", ";
|
||||
}
|
||||
//ss<<"
|
||||
";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
Stack Stack::operator=(const Stack &stk){
|
||||
length=stk.length;
|
||||
top=stk.top;
|
||||
|
||||
if(p!=0)
|
||||
delete [] p;
|
||||
try{
|
||||
p=new int[length];
|
||||
}catch(bad_alloc ba){
|
||||
throw StackException("Memory fault in copying!
|
||||
");
|
||||
}
|
||||
for(int i=0;i<length;i++)
|
||||
p[i]=stk.p[i];
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
ostream& operator<<(ostream &o,Stack &s){
|
||||
o<<s.str();
|
||||
return o;
|
||||
}
|
||||
|
||||
} // namespace stk;
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
Another example of a conversion function
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
class Power {
|
||||
double b;
|
||||
int e;
|
||||
double val;
|
||||
public:
|
||||
Power(double base, int exp);
|
||||
Power operator+(Power o) {
|
||||
double base;
|
||||
int exp;
|
||||
base = b + o.b;
|
||||
exp = e + o.e;
|
||||
Power temp(base, exp);
|
||||
return temp;
|
||||
}
|
||||
operator double() { return val; } // convert to double
|
||||
};
|
||||
Power::Power(double base, int exp)
|
||||
{
|
||||
b = base;
|
||||
e = exp;
|
||||
val = 1;
|
||||
if(exp==0)
|
||||
return;
|
||||
for( ; exp>0; exp--)
|
||||
val = val * b;
|
||||
}
|
||||
int main()
|
||||
{
|
||||
Power x(4.0, 2);
|
||||
double a;
|
||||
a = x; // convert to double
|
||||
cout << x + 100.2; // convert x to double and add 100.2
|
||||
cout << "\n";
|
||||
Power y(3.3, 3), z(0, 0);
|
||||
z = x + y; // no conversion
|
||||
a = z; // convert to double
|
||||
cout << a;
|
||||
return 0;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
Another example of read() and write() and illustrates the use of gcount( )
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
double doubleNumberArray[4] = {99.75, -34.4, 1776.0, 200.1};
|
||||
int i;
|
||||
ofstream out("numbers", ios::out | ios::binary);
|
||||
if(!out) {
|
||||
cout << "Cannot open file.";
|
||||
return 1;
|
||||
}
|
||||
out.write((char *) &doubleNumberArray, sizeof doubleNumberArray);
|
||||
out.close();
|
||||
for(i=0; i<4; i++) // clear array
|
||||
doubleNumberArray[i] = 0.0;
|
||||
|
||||
ifstream in("numbers", ios::in | ios::binary);
|
||||
in.read((char *) &doubleNumberArray, sizeof doubleNumberArray);
|
||||
|
||||
cout << in.gcount() << " bytes read\n"; // see how many bytes have been read
|
||||
for(i=0; i<4; i++) // show values read from file
|
||||
cout << doubleNumberArray[i] << " ";
|
||||
in.close();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
Append two strings
|
||||
#include <iostream>
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
|
||||
#include <string>
|
||||
using std::string;
|
||||
|
||||
int main()
|
||||
{
|
||||
string string1( "cat" );
|
||||
string string3;
|
||||
|
||||
string3.assign( string1 );
|
||||
|
||||
cout << "string1: " << string1
|
||||
<< "\nstring3: " << string3 << "\n\n";
|
||||
|
||||
|
||||
string3 += "pet";
|
||||
string3.append( string1, 1, string1.length() - 1 );
|
||||
|
||||
cout << "string1: " << string1
|
||||
<< "\nstring3: " << string3 << "\n\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
Appending to the End of a File
|
||||
#include <iostream>
|
||||
|
||||
#include <fstream>
|
||||
using namespace std;
|
||||
int main(){
|
||||
char fileName[80];
|
||||
char buffer[255];
|
||||
cout << "Please re-enter the file name: ";
|
||||
cin >> fileName;
|
||||
|
||||
ifstream fin(fileName);
|
||||
if (fin){
|
||||
char ch;
|
||||
while (fin.get(ch))
|
||||
cout << ch;
|
||||
}
|
||||
fin.close();
|
||||
|
||||
cout << "in append mode...\n";
|
||||
|
||||
ofstream fout(fileName,ios::app);
|
||||
if (!fout)
|
||||
{
|
||||
cout << "Unable to open for appending.\n";
|
||||
return(1);
|
||||
}
|
||||
|
||||
cout << "\nEnter text for the file: ";
|
||||
cin.ignore(1,'\n');
|
||||
cin.getline(buffer,255);
|
||||
fout << buffer << "\n";
|
||||
fout.close();
|
||||
|
||||
fin.open(fileName);
|
||||
if (!fin)
|
||||
{
|
||||
cout << "Unable to open for reading.\n";
|
||||
return(1);
|
||||
}
|
||||
char ch;
|
||||
while (fin.get(ch))
|
||||
cout << ch;
|
||||
fin.close();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
Appending values to Vector Containers after sorting
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
template <class T>
|
||||
void print(T& c){
|
||||
for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
|
||||
std::cout << *i << endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main( ){
|
||||
const char* names1[] = { "A", "B", "C" };
|
||||
const char* names2[] = { "D", "E", "F", "G" };
|
||||
|
||||
vector<string> squad1( names1,names1 + sizeof( names1 ) / sizeof( names1[0] ) );
|
||||
vector<string> squad2( names2,names2 + sizeof( names2 ) / sizeof( names2[0] ) );
|
||||
|
||||
sort( squad1.begin(), squad1.end() );
|
||||
|
||||
print( squad1);
|
||||
sort( squad2.begin(), squad2.end() );
|
||||
print( squad2);
|
||||
|
||||
squad1.insert( squad1.end(), squad2.begin(), squad2.end() );
|
||||
print( squad1);
|
||||
|
||||
sort( squad1.begin(), squad1.end() );
|
||||
print( squad1);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
Applying Generic Functions: A Generic Bubble Sort
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
template <class X> void bubble(
|
||||
X *items, // pointer to array to be sorted
|
||||
int count) // number of items in array
|
||||
{
|
||||
register int a, b;
|
||||
X t;
|
||||
|
||||
for(a=1; a<count; a++)
|
||||
for(b=count-1; b>=a; b--)
|
||||
if(items[b-1] > items[b]) {
|
||||
// exchange elements
|
||||
t = items[b-1];
|
||||
items[b-1] = items[b];
|
||||
items[b] = t;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int iarray[7] = {7, 5, 4, 3, 9, 8, 6};
|
||||
double darray[5] = {4.3, 2.5, -0.9, 100.2, 3.0};
|
||||
|
||||
for(int i=0; i<7; i++)
|
||||
cout << iarray[i] << endl;
|
||||
|
||||
for(int i=0; i<5; i++)
|
||||
cout << darray[i] << endl;
|
||||
|
||||
bubble(iarray, 7);
|
||||
bubble(darray, 5);
|
||||
|
||||
for(int i=0; i<7; i++)
|
||||
cout << iarray[i] << endl;
|
||||
|
||||
for(int i=0; i<5; i++)
|
||||
cout << darray[i] << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
Applying Template Classes: A Generic Array Class
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
using namespace std;
|
||||
|
||||
const int SIZE = 10;
|
||||
|
||||
template <class T> class MyClass {
|
||||
T a[SIZE];
|
||||
public:
|
||||
MyClass() {
|
||||
register int i;
|
||||
for(i=0; i<SIZE; i++) a[i] = i;
|
||||
}
|
||||
T &operator[](int i);
|
||||
};
|
||||
|
||||
template <class T> T &MyClass<T>::operator[](int i)
|
||||
{
|
||||
if(i<0 || i> SIZE-1) {
|
||||
cout << "\nIndex value of ";
|
||||
cout << i << " is out-of-bounds.\n";
|
||||
exit(1);
|
||||
}
|
||||
return a[i];
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
MyClass<int> intob; // integer array
|
||||
MyClass<double> doubleob; // double array
|
||||
|
||||
for(int i=0; i<SIZE; i++) intob[i] = i;
|
||||
for(int i=0; i<SIZE; i++) cout << intob[i] << endl;
|
||||
|
||||
for(int i=0; i<SIZE; i++) doubleob[i] = (double) i/3;
|
||||
for(int i=0; i<SIZE; i++) cout << doubleob[i] << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
Area of rectangle
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
const double pi = 3.14159;
|
||||
|
||||
int main()
|
||||
{
|
||||
float length, width, area;
|
||||
|
||||
cout << "Enter The Length Of The Rectangle: ";
|
||||
cin >> length;
|
||||
cout << "Enter The Width Of Rectangle: ";
|
||||
cin >> width;
|
||||
area = length*width;
|
||||
|
||||
cout <<"The area of the rectangle is : "<< area << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Area overloded
|
||||
|
||||
#include<iostream.h>
|
||||
#include<conio.h>
|
||||
#define phi 3.14
|
||||
int area(int,int);
|
||||
float area(int);
|
||||
void main()
|
||||
{
|
||||
int a,b,c,cho;
|
||||
clrscr();
|
||||
cout<<"\t What do you want to do?\n";
|
||||
cout<<"1. area of rectangle"<<endl;
|
||||
cout<<"2. area of circle"<<endl;
|
||||
cout<<"Choice:";
|
||||
cin>>cho;
|
||||
switch(cho)
|
||||
{
|
||||
case 1:
|
||||
cout<<"Enter lengt and breath (with white space):";
|
||||
cin>>a>>b;
|
||||
cout<<"Area of RECTANGLE:"<<area(a,b);
|
||||
break;
|
||||
case 2:
|
||||
cout<<"Enter radius:";
|
||||
cin>>c;
|
||||
cout<<"Area of CIRCLE:"<<area(c);
|
||||
break;
|
||||
}
|
||||
getch();
|
||||
}
|
||||
int area(int x,int y)
|
||||
{
|
||||
return (x*y);
|
||||
}
|
||||
float area(int s)
|
||||
{
|
||||
return (phi*s*s);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
Arithmetic assignment operators
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main() {
|
||||
int ans = 27;
|
||||
|
||||
ans += 10; //same as: ans = ans + 10;
|
||||
cout << ans << ", ";
|
||||
ans -= 7; //same as: ans = ans - 7;
|
||||
cout << ans << ", ";
|
||||
ans *= 2; //same as: ans = ans * 2;
|
||||
cout << ans << ", ";
|
||||
ans /= 3; //same as: ans = ans / 3;
|
||||
cout << ans << ", ";
|
||||
ans %= 3; //same as: ans = ans % 3;
|
||||
cout << ans << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
Array Initialization
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main ()
|
||||
{
|
||||
char name[ ] = {'J', 'e', 'f', 'f', '/0' };
|
||||
|
||||
cout << name;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
Array based on int pointer
|
||||
#include <iostream>
|
||||
#include <stdlib.h>
|
||||
using namespace std;
|
||||
class array
|
||||
{
|
||||
int *p;
|
||||
int size;
|
||||
public:
|
||||
array(int sz) {
|
||||
p = new int[sz];
|
||||
if(!p) exit(1);
|
||||
size = sz;
|
||||
}
|
||||
~array() {delete [] p;}
|
||||
array(const array &object);
|
||||
void put(int i, int j){
|
||||
if(i>=0 && i<size)
|
||||
p[i] = j;
|
||||
}
|
||||
int get(int i) {return p[i];}
|
||||
};
|
||||
|
||||
array::array(const array &object)
|
||||
{
|
||||
int lcl_i;
|
||||
|
||||
p = new int[object.size];
|
||||
if (!p)
|
||||
exit(1);
|
||||
for(lcl_i=0; lcl_i < object.size; lcl_i++)
|
||||
p[lcl_i] = object.p[lcl_i];
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
array num(10);
|
||||
int lcl_i;
|
||||
|
||||
for (lcl_i=0; lcl_i<10; lcl_i++)
|
||||
num.put(lcl_i, lcl_i);
|
||||
for (lcl_i=9; lcl_i>=0; lcl_i--)
|
||||
cout << num.get(lcl_i);
|
||||
cout << endl;
|
||||
|
||||
// Create another array using the copy constructor
|
||||
array x=num;
|
||||
for (lcl_i=0; lcl_i<10; lcl_i++)
|
||||
cout << x.get(lcl_i);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
Array class for 10 int value with overloaded functions: +, -, ==
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class array {
|
||||
int nums[10];
|
||||
public:
|
||||
array();
|
||||
void set(int n[10]);
|
||||
void show();
|
||||
array operator+(array object2);
|
||||
array operator-(array object2);
|
||||
int operator==(array object2);
|
||||
};
|
||||
|
||||
array::array()
|
||||
{
|
||||
int i;
|
||||
for(i = 0; i <10; i++) nums[ i ] = 0;
|
||||
}
|
||||
|
||||
void array::set(int *n)
|
||||
{
|
||||
int i;
|
||||
|
||||
for(i = 0; i <10; i++) nums[ i ] = n[ i ];
|
||||
}
|
||||
|
||||
void array::show()
|
||||
{
|
||||
int i;
|
||||
|
||||
for(i = 0; i <10; i++)
|
||||
cout << nums[ i ] << ' ';
|
||||
|
||||
cout << endl;
|
||||
}
|
||||
|
||||
array array::operator+(array object2)
|
||||
{
|
||||
int i;
|
||||
array temp;
|
||||
|
||||
for(i = 0; i <10; i++)
|
||||
temp.nums[ i ] = nums[ i ] + object2.nums[ i ];
|
||||
|
||||
return temp;
|
||||
}
|
||||
|
||||
array array::operator-(array object2)
|
||||
{
|
||||
int i;
|
||||
array temp;
|
||||
|
||||
for(i = 0; i <10; i++)
|
||||
temp.nums[ i ] = nums[ i ] - object2.nums[ i ];
|
||||
|
||||
return temp;
|
||||
}
|
||||
|
||||
int array::operator==(array object2)
|
||||
{
|
||||
int i;
|
||||
|
||||
for(i = 0; i <10; i++)
|
||||
if(nums[ i ]!=object2.nums[ i ]) return 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
array object1, object2, object3;
|
||||
|
||||
int i[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
||||
|
||||
object1.set(i);
|
||||
object2.set(i);
|
||||
|
||||
object3 = object1 + object2;
|
||||
object3.show();
|
||||
|
||||
object3 = object1 - object3;
|
||||
object3.show();
|
||||
|
||||
if(object1==object2)
|
||||
cout << "object1 equals object2\n";
|
||||
else
|
||||
cout << "object1 does not equal object2\n";
|
||||
|
||||
if(object1==object3)
|
||||
cout << "object1 equals object3\n";
|
||||
else
|
||||
cout << "object1 does not equal object3\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
Arrays of Objects
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
class MyClass {
|
||||
int i;
|
||||
public:
|
||||
void setInt(int j) {
|
||||
i=j;
|
||||
}
|
||||
int getInt() {
|
||||
return i;
|
||||
}
|
||||
};
|
||||
int main()
|
||||
{
|
||||
MyClass myObject[3];
|
||||
int i;
|
||||
for(i=0; i<3; i++)
|
||||
myObject[i].setInt(i+1);
|
||||
for(i=0; i<3; i++)
|
||||
cout << myObject[i].getInt() << "\n";
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
Ask for a persons name, and generate a framed greeting
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << "Please enter your first name: ";
|
||||
std::string name;
|
||||
std::cin >> name;
|
||||
|
||||
const std::string greeting = "Hello, " + name + "!";
|
||||
const std::string spaces(greeting.size(), ' ');
|
||||
const std::string second = "* " + spaces + " *";
|
||||
|
||||
const std::string first(second.size(), '*');
|
||||
|
||||
std::cout << std::endl;
|
||||
std::cout << first << std::endl;
|
||||
std::cout << second << std::endl;
|
||||
std::cout << "* " << greeting << " *" << std::endl;
|
||||
std::cout << second << std::endl;
|
||||
std::cout << first << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
Assign Items in int array to vector
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <cassert>
|
||||
#include <numeric> // for accumulate
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int x[5] = {2, 3, 5, 7, 11};
|
||||
|
||||
vector<int> vector1(&x[0], &x[5]);
|
||||
|
||||
int sum = accumulate(vector1.begin(), vector1.end(), 0);
|
||||
|
||||
cout << sum << endl;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
28
|
||||
|
||||
*/
|
||||
@@ -0,0 +1,24 @@
|
||||
Assign elements in vector a value through an iterator
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <cctype>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<char> v(10); // create a vector of length 10
|
||||
vector<char>::iterator p; // create an iterator
|
||||
int i;
|
||||
|
||||
// assign elements in vector a value
|
||||
p = v.begin();
|
||||
i = 0;
|
||||
while(p != v.end()) {
|
||||
*p = i + 'a';
|
||||
p++;
|
||||
i++;
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
Assign object1 to object2
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class BaseClass {
|
||||
int a;
|
||||
public:
|
||||
void load_a(int n) {
|
||||
a = n;
|
||||
}
|
||||
int get_a() {
|
||||
return a;
|
||||
}
|
||||
};
|
||||
|
||||
class DerivedClass : public BaseClass {
|
||||
int b;
|
||||
public:
|
||||
void load_b(int n) {
|
||||
b = n;
|
||||
}
|
||||
int get_b() {
|
||||
return b;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
DerivedClass object1, object2;
|
||||
|
||||
object1.load_a(5);
|
||||
object1.load_b(10);
|
||||
|
||||
|
||||
object2 = object1;
|
||||
|
||||
cout << "Here is object1's a and b: ";
|
||||
cout << object1.get_a() << ' ' << object1.get_b() << endl;
|
||||
|
||||
cout << "Here is object2's a and b: ";
|
||||
cout << object2.get_a() << ' ' << object2.get_b() << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
Assign values using the member initialization syntax
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class MyClass {
|
||||
const int numA; // const member
|
||||
const int numB; // const member
|
||||
public:
|
||||
// Initialize numA and numB using initialization syntax.
|
||||
MyClass(int x, int y) : numA(x), numB(y) { }
|
||||
int getNumA() {
|
||||
return numA;
|
||||
}
|
||||
int getNumB() {
|
||||
return numB;
|
||||
}
|
||||
};
|
||||
int main()
|
||||
{
|
||||
MyClass object1(7, 9), object2(5, 2);
|
||||
cout << "Values in object1 are " << object1.getNumB() << " and " << object1.getNumA() << endl;
|
||||
cout << "Values in object2 are " << object2.getNumB() << " and " << object2.getNumA() << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
Assigning and Displaying Array Values
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main ()
|
||||
{
|
||||
int testScore[3];
|
||||
|
||||
cout << "Enter test score #1: ";
|
||||
|
||||
cin >> testScore[0];
|
||||
|
||||
cout << "Enter test score #2: ";
|
||||
|
||||
cin >> testScore[1];
|
||||
|
||||
cout << "Enter test score #3: ";
|
||||
|
||||
cin >> testScore[2];
|
||||
|
||||
cout << "Test score #1: " << testScore[0] << endl;
|
||||
|
||||
cout << "Test score #2: " << testScore[1] << endl;
|
||||
|
||||
cout << "Test score #3: " << testScore[2] << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
Assigning deque objects.
|
||||
#include <iostream>
|
||||
#include <deque>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
deque<char> dequeObject1(10), dequeObject2;
|
||||
int i;
|
||||
|
||||
for(i = 0; i <10; i++)
|
||||
dequeObject1[i] = i + 'A';
|
||||
cout << "Contents of dequeObject1 are: ";
|
||||
for(i = 0; i <dequeObject1.size(); i++)
|
||||
cout << dequeObject1[i];
|
||||
cout << "\n\n";
|
||||
|
||||
// assign one deque to another
|
||||
dequeObject2 = dequeObject1;
|
||||
|
||||
cout << "Size of dequeObject2 is " << dequeObject2.size() << endl;
|
||||
cout << "Contents of dequeObject2 are: ";
|
||||
for(i = 0; i <dequeObject2.size(); i++)
|
||||
cout << dequeObject2[i];
|
||||
cout << "\n\n";
|
||||
|
||||
dequeObject2.assign(dequeObject1.begin()+2, dequeObject1.end()-2);
|
||||
|
||||
cout << "Size of dequeObject2 is " << dequeObject2.size() << endl;
|
||||
cout << "Contents of dequeObject2 are: ";
|
||||
for(i = 0; i <dequeObject2.size(); i++)
|
||||
cout << dequeObject2[i];
|
||||
cout << "\n\n";
|
||||
|
||||
dequeObject2.assign(8, 'X');
|
||||
|
||||
cout << "Size of dequeObject2 is " << dequeObject2.size() << endl;
|
||||
cout << "Contents of dequeObject2 are: ";
|
||||
for(i = 0; i <dequeObject2.size(); i++)
|
||||
cout << dequeObject2[i];
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
Average function
|
||||
|
||||
#include <iostream>
|
||||
#include <stdlib.h>
|
||||
int Average(int i)
|
||||
{
|
||||
static int sum = 0, count = 0;
|
||||
sum = sum + i;
|
||||
count++;
|
||||
return sum / count;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
int num;
|
||||
do{
|
||||
|
||||
cout<<"Enter numbers ( -1 to quit )"<<endl;
|
||||
cin>>num;
|
||||
/*if number is not -1 print the average*/
|
||||
if(num != -1)
|
||||
cout<<"The average is "<<Average(num)<<endl;
|
||||
|
||||
|
||||
}while(num>-1);
|
||||
return 0;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user