What are special operators in c plus plus?
The only "special" operators in C++ are those that cannot be overloaded. That is; the dot member operator (.), pointer to member operator (.*), ternary conditional operator (:?), scope resolution operator (::), sizeof() and typeof().
Create a class to represent a student:
struct student {
string fname;
string lname;
unsigned age;
unsigned id;
};
Overload operator< to compare two student objects:
bool operator< (const student& a, const student& b) {
return a.lname<b.lname;
}
Overload std::ostream::operator<< to print a student:
std::ostream& operator<< (std::ostream& os, const student& s) {
return os << s.fname << ' ' << s.lname << ' ' << s.age << ' ' << s.id;
}
Now you can write your program:
int main() {
std::vector<student> v;
for (unsigned count=0; count<100;) {
student s;
std::cout << "Enter details for student #" << ++count;
std::cout << "First name: ";
std::cin >> s.fname; std::cout << "Last name: ";
std::cin >> s.lname;
std::cout << "Age: ";
std::cin >> s.age;
std::cout << "ID: ";
std::cin >> s.id;
v.push_back (s);
}
std::cout << "Sorting..."
std::sort (v.begin(), v.end());
std::cout << "\n\n";
// Print students...
for (auto s : v) std::cout << s << std::endl;
}
What a c plus plus program that solve the tower of hanoi problem of n disk?
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std; // For std::cout and std::endl
// Each rod in the tower has a variable number of rings.
typedef vector<size_t> Rod;
// Displays the tower.
void display(Rod tower[], size_t move=0)
{
if(!move)
cout<<"Initial Position";
else
cout<<"Move "<<move;
cout<<":\n"<<endl;
static const char label[]="ABC";
for(size_t rod=0; rod<3; ++rod)
{
cout<<label[rod]<<":";
for(size_t ring=0; ring<tower[rod].size(); ++ring)
cout<<" "<<tower[rod][ring];
cout<<endl;
}
cout<<endl;
}
int main()
{
cout<<"Tower of Hannoi\n===============\n"<<endl;
size_t rings=1;
do
{
if( rings<1 rings>9 )
cout<<"You must enter a value in the range 1..9.\n"<<endl;
cout<<"Enter the no. of rings (1..9): ";
string input;
getline(cin, input);
stringstream(input)>>rings;
cout<<endl;
}while(rings<1 rings>9);
// Instantiate the three towers.
Rod tower[3];
// Push all the rings onto the 1st tower (largest to smallest)
// and display the initial position.
for(size_t ring=0; ring<rings; ++ring)
tower[0].push_back(rings-ring);
display(tower);
// Determine the minimum no. of moves required
// (2 raised to the power of rings, minus 1).
size_t moves=(1<<rings)-1;
// Determine if the number of rings is odd or even.
size_t odd=rings&1;
// Begin moving rings...
size_t move=0;
while(move<moves)
{
// Determine which 2 of the 3 rods to compare.
size_t rod_index1=0, rod_index2=odd?1:2;
switch(move%3)
{
case(0): rod_index2=odd?2:1; break;
case(2): rod_index1=odd?2:1; break;
}
// Reference the two rods.
Rod& rod1=tower[rod_index1];
Rod& rod2=tower[rod_index2];
// Obtain the top-most ring sizes (0 if rod is empty).
size_t ring1=rod1.size()?*rod1.rbegin():0;
size_t ring2=rod2.size()?*rod2.rbegin():0;
// Invariant: ring1 + ring2 > 0.
// Move the smallest ring to the other rod.
if(!ring2 (ring1 && ring1<ring2))
{
rod1.pop_back();
rod2.push_back(ring1);
}
else
{
rod2.pop_back();
rod1.push_back(ring2);
}
// Display the result of the move.
display(tower, ++move);
}
// Finished!
cout<<"Complete in "<<moves<<" moves!\n"<<endl;
}
How to wite the codes in C plus plus enter 4 integers?
#include<iostream>
int main()
{
int n[4];
std::cout << "Enter 4 integers: "
std::cin >> n[0] >> n[1] >> n[2] >> n[3];
}
The above is naive because there's no error-checking to prevent garbage input. A better solution is to input 4 strings and then convert those strings to integers. If the conversion fails, simply ask for new input until the conversion succeeds. The following shows one method of achieving this:
#include<iostream>
#include<sstream>
int main()
{
int n[4];
// repeat until valid
bool valid {false};
while (!valid)
{
// create 4 temporary strings for input
std::string s[4];
std::cout << "Enter 4 integers: "
std::cin >> s[0] >> s[1] >> s[2] >> s[3];
// assume input is valid until proven otherwise
valid = true;
for (size_t i=0; valid && i<4; ++i)
{
// convert the current string to an integer
std::stringstream ss {s[i]};
valid = (ss >> n[i]);
}
}
// When we reach here, n[] will contain 4 valid integers.
// Use n[] ...
}
To delete an element form an array you simply move everything one place to the left, starting with the element to the right of the element you wish to remove, and then delete the final element by resizing the array. The following code demonstrates this:
#include <iostream>
void DeleteElement(unsigned int** pp,unsigned int& size,unsigned int index)
{
if(size)
{
unsigned int* p=*pp+index;
unsigned int* c=p+1;
std::cout<<"Deleting element index "<<index<<" with value "<<*p<<" from an array of size "<<size<<std::endl;
--size;
while(index++<size)
*p++=*c++;
*pp=(unsigned int*)realloc(*pp,size*sizeof(unsigned int));
}
}
void PrintArray(unsigned int* a,const unsigned int size)
{
std::cout<<"Array: size="<<size<<" { ";
unsigned int i=0;
while(i<size)
std::cout<<a[i++]<<" ";
std::cout<<"} "<<std::endl;
}
int main()
{
// Allocate a dynamic array of size 5:
unsigned int size=5;
unsigned int* a=(unsigned int*)malloc(size*sizeof(unsigned int));
// Initialise array with sorted values (ascending order):
for(unsigned int i=0;i<size;++i)
a[i]=(i+1)*2;
// Print current array:
PrintArray(a,size);
// Delete element 1 (value 2)
DeleteElement(&a,size,1);
// Print current array:
PrintArray(a,size);
// Delete element 2 (value 4)
DeleteElement(&a,size,2);
// Print current array:
PrintArray(a,size);
// Release allocation.
delete[]a, a=NULL;
return(0);
}
Note that static arrays cannot be resized, so to remove an element you need to maintain a count of the active elements, and move inactive elements to the end of the array. The process is similar to the above, except you need to copy the inactive element's value before shifting everything to the left, and then replace the final element's value with the one you saved.
In C++, operations such as this are greatly simplified by using a vector rather than an array. Vectors are effectively the same as dynamic arrays, but are implemented as self-contained objects with member methods to manipulate the contents, thus greatly simplifying your code. Deleting an element is a simple as calling the vector's built-in delete method. Memory management is largely transparent and, because a vector knows its internal size, passing vectors to functions is made that much easier -- you simply pass them by reference.
Can a basic data type be converted into user defined data type in c?
Yes, but it cannot be done in C as intuitively as it can be done in C++:
struct X {
X (const int i): m {i} {} // converts an int to an X [C++ only]
X& operator= (const int i) { m=i; return *this; } // assign an int to an X [C++ only]
int m;
};
Usage:
X x {42}; // construct X from int
x = 0; // assign an int to an X
In C we must use a conversion function:
struct X convert (const int i) { // convert an int to an X
struct X;
x.m = i;
return x;
}
Usage:
struct X x;
x = convert (42);
What is the marxist structure?
Marxism is the political philosophy and practice derived from the work of Karl Marx and Friedrich Engels. Any political practice or theory that is based on an interpretation of the works of Marx and Engels may be called Marxism. There is still a significant[citation needed] and vital[citation needed] presence of marxist approaches in academic fields of research, trailing almost as an afterthought; these include anthropology, media studies, Theatre, history, economics, literary criticism, aesthetics and philosophy.[1] The constitution of the Communist Parties and Communist states was grounded in Marxism; the basic difference between Communism in general and Marxism, is that Communism aims at the realization of a "Communist society", while Marxism is a theoretical-practical framework based on the analysis of "the conflicts between the powerful and the subjugated".[2][3] As a consequence of this, there are many scholars and thinkers who use Marxism as a framework for analysis but do not advocate a communist society. While there are many theoretical and practical differences among the various forms of Marxism, most forms of Marxism share: * a belief that capitalism is based on the exploitation of workers by the owners of capital * a belief that people's consciousness of the conditions of their lives reflects material conditions and relations * an understanding of class in terms of differing relations of production, and as a particular position within such relations * an understanding of material conditions and social relations as historically malleable * a view of history according to which class struggle, the evolving conflict between classes with opposing interests, structures each historical period and drives historical change
What is difference between getimage and putimage in c plus plus?
#include <iostream.h>
#include <conio.h>
# include <process.h> //exit(0)
# include <dos.h>
# include <stdlib.h>
# include <graphics.h>
# include <stdio.h>
int MaxX, MaxY, MidX, MidY ;
int bri[5][20] ;
bricks(); //to display bricks and paddle and bulb rounded form
delbrick(int,int);
int graphmode= CGAHI, graphdriver = CGA; //CGAHI = 640 x 200 (col x row)
void MousePos(int* x)
{ union REGS in,out;
in.x.ax=3;
int86(0x33,&in,&out);
*x=(int)out.x.cx;
}
main()
{
int BallX, BallY, Base1, Base2, dx = 1, dy = -1, OldX, OldY ;
int totallayer[5] = { 10, 20, 30, 40, 50 }, max = 50, layer = 4 ;
int i, flag = 0, speed = 10, score = 0, chance = 4, areareq ;
char *m1, *m2 ; //pointers to memory
initgraph ( &graphdriver, &graphmode, "c:\\tc\\bgi" ) ;
MaxX = getmaxx() ;
MaxY = getmaxy() ;
MidX = MaxX / 2 ;
MidY = MaxY / 2 ;
/* draw the four layer of bricks, the paddle and the ball */
rectangle ( 0, 0, MaxX, MaxY - 12 ) ;
bricks() ;
rectangle ( MidX - 25, MaxY - 19, MidX + 25, MaxY - 12 ) ;
circle ( MidX, MaxY -25, 12 ) ;
/* memory allocation for storing the image of the ball */
areareq = imagesize ( MidX - 12, MaxY - 18, MidX + 12, MaxY - 8 ) ;
m1 =((char*) malloc ( areareq )) ;
/* memory allocation for storing the image of the paddle */
areareq = imagesize ( MidX - 25, MaxY - 7, MidX + 25, MaxY - 1 ) ;
m2 =((char *) malloc ( areareq ) );
/* image of the paddle and the ball is stored into allocated memory */
getimage ( MidX - 12, MaxY - 7 - 12 - 12 + 1, MidX + 12, MaxY - 8 -12,m1 ) ;
getimage ( MidX - 25, MaxY - 7 - 12, MidX + 25, MaxY - 1 - 12, m2 ) ;
/* store current position of the paddle and ball */
Base1 = MidX - 25 ;
Base2 = MaxY - 19 ;
BallX = MidX - 12 ;
BallY = MaxY - 7 - 12 + 1 - 12 ;
/* display balls remaining ( initially 3 ) */
gotoxy ( 45, 25 ) ;
cout<< "Balls :" ;
for ( i = 0 ; i < 3 ; i++ )
{
circle ( 515 + i * 35, MaxY - 5, 12 ) ;
}
/* display starting score */
gotoxy ( 1, 25 ) ;
cout<< "Score: ";
gotoxy(16,25);
cout<<score;
while ( !kbhit() )
{
flag = 0 ;
/* saving current x and y coordinates of the ball */
OldX = BallX ;
OldY = BallY ;
/* update ballx and bally to move the ball in correct direction */
BallX = BallX + dx ;
BallY = BallY + dy ;
/* according to the position of ball the layer of bricks isdetermined*/
if ( BallY > 40 )
{
max = 50 ;
layer = 4 ;
}
else
{
if ( BallY > 30 )
{
max = 40 ;
layer = 3 ;
}
else
{
if ( BallY > 20 )
{
max = 30 ;
layer = 2 ;
}
else
{
if ( BallY > 10 )
{
max = 20 ;
layer = 1 ;
}
else
{
max = 10 ;
layer = 0 ;
}
}
}
}
/* if the ball hits the right boundary, move it to the left */
if ( BallX > ( MaxX - 24 - 1 ) )
{
BallX = MaxX - 24 - 1 ;
dx = -dx ;
}
/* if the ball hits the left boundary, move it to the right */
if ( BallX < 1 )
{
BallX = 1 ;
dx = -dx ;
}
/* if the ball hits the top boundary, move it down */
if ( BallY < 1 )
{
BallY = 1 ;
dy = -dy ;
}
/* if the ball is in the area of the bricks */
if ( BallY < max )
{
/* if there is no brick at the top of the ball */
if ( bri[layer][ ( BallX + 10 ) / 32 ] 800 - ( ( 4 - chance ) * 10 ) )
{
outtextxy ( MidX, MidY, "Winner !!" ) ;
if ( score < 800 )
outtextxy ( MidX, MidY + 30, "Try to score 800" ) ;
else
outtextxy ( MidX, MidY + 30, " GREAT!" ) ;
closegraph() ;
restorecrtmode() ;
exit ( 0 ) ;
}
/* introduce delay for few seconds */
delay ( speed ) ;
/* put the image of the paddle at the old coordinates */
putimage ( Base1, Base2, m2, OR_PUT ) ;
/* erase the image of the paddle at the old coordinates */
putimage ( Base1, Base2, m2, XOR_PUT ) ;
MousePos(&Base1);
/* if paddle goes beyond left boundary */
if ( Base1 < 1 )
Base1 = 1 ;
/* if paddle goes beyond right boundary */
if ( Base1 > 588 )
Base1 = 588 ;
/* put the image of the paddle at the proper position */
putimage ( Base1, Base2, m2, XOR_PUT ) ;
}
closegraph(); /* Return the system to text mode */
return(0);
}
bricks()
{
int i, j, lx = 0, ly = 0 ;
for ( i = 0 ; i < 5 ; i++ ) /* 5 rows */
{
for ( j = 0 ; j < 20 ; j++ ) /* 20 columns */
{
rectangle ( lx, ly, lx + 20, ly + 7 ) ;
floodfill ( lx + 1, ly + 1, 2 ) ;
lx = lx + 32 ;
}
lx = 0 ;
ly = ly + 10 ;
}
}
delbrick ( int b, int l )
{
/* b - brick number, l - layer */
setcolor ( BLACK ) ;
rectangle ( b * 32, l * 10, ( b * 32 ) + 20 , ( l * 10 ) + 7 ) ;
rectangle ( b * 32 + 1, l * 10, ( b * 32 ) + 20 - 1, ( l * 10 ) + 7 -1 );
rectangle ( b * 32 + 2, l * 10, ( b * 32 ) + 20 - 2, ( l * 10 ) + 7 -2 );
rectangle ( b * 32 + 3, l * 10, ( b * 32 ) + 20 - 3, ( l * 10 ) + 7 -3 );
rectangle ( b * 32 + 4, l * 10, ( b * 32 ) + 20 - 4, ( l * 10 ) + 7 -4 );
rectangle ( b * 32 + 5, l * 10, ( b * 32 ) + 20 - 5, ( l * 10 ) + 7 -5 );
rectangle ( b * 32 + 6, l * 10, ( b * 32 ) + 20 - 6, ( l * 10 ) + 7 -6 );
setcolor ( CGA_YELLOW ) ;
}
How can I initialize a type that is a pointer to a struct in Go?
For the purpose of clarification, you cannot initialise types, you can only initialise variables (or constants) of a type. A variable (or constant) is known as an "instance" or "object" of the type. All instances of a type must be named. A pointer variable allows us to "refer" to a named object of the pointer's type. this is achieved by storing the memory address (the starting address) of that object. By changing the address stored in the pointer variable, the same pointer variable can be used to refer to different objects in memory. This is useful when passing objects to functions because if we pass objects directly (by name), the function receives a copy of the object. This is known as "pass by value". However, when a function expects a pointer variable rather than a named variable, the address of the object is copied instead. This is known as "pass by reference" and allows the function to operate (indirectly) upon the object being referenced rather than a copy of the object (any changes to a copy are not reflected in the original object).
Passing by reference is particularly useful when the object is large and complex. To improve efficiency, we must avoid making any unnecessary copies of large or complex objects. Functions that do not modify an object are a prime example; there is no point in copying an object that will not be modified. If we wish a function to modify the object, we must pass the object by reference. The only time we should copy an object is when we're not interested in the modifications made by a function, or when we want to compare the changes that were made. In these cases we simply make a copy of the object before passing that copy to the function by reference. When working with concurrency, however, it is best to use pass by value semantics. In this way, each thread works with a local copy of your object, and thus avoids "race conditions", where one task is accessing an object that is being modified by another task, which can lead to unpredictable results.
Pointer variables are said to "point at" the memory the refer to (hence they are called pointers). To access the value being pointed at, the pointer variable must be dereferenced. However, in the case of pointer to struct variables, the dereferencing is transparent.
All variables in Go are implicitly initialised with the default "zero" value for its type. The zero value of a pointer variable is always "nil" (regardless of which type of pointer). You must never dereference a pointer variable that holds the nil value so always check the pointer is non-nil. Equally, you must never dereference a pointer to an object that no longer exists in memory. Always nil your pointers as soon as you are finished with them.
The following example demonstrates how to initialise a pointer variable to a struct:
package main
import "fmt"
type Point struct {
X int
Y int
}
func main () {
v := Point{1, 2} // instantiate an object of type Point
p := &v // assign the address of v to pointer p (p's type is inferred from v)
fmt.Println(*p) // print the indirect value of v (dereference p)
}
2 examples of fields in a database holding details about school pupils?
A Table field is one that stores the data corresponding to one attribute of the table. for a school student db it might be roll number, name, date of birth, grade etc.
Ex:
Name Roll No. Age Grade
John 101 12 5
Julie 102 12 5
Here name, roll no, age etc are fields
How do you merge two linked list without using any temporary variable?
You can either insert one list directly into the other, or you can create a completely new list and insert the two lists one after the other. Neither method requires a temporary variable. Temporaries are only required when you need to swap one list for another, but you can minimise this requirement by using "move semantics", where the lists can simply swap their resources, not the elements themselves. In this way, only one temporary is required.
What is the difference between In line Function and Preprocessed in c plus plus?
An inline function is one where the compiler substitutes the body of the function for its invocation. By doing this, the compiler avoids the cost of setting up and tearing down a function call. This is most effective when dealing with small, one or two line, functions.
A preprocessor macro does the same thing, except that the main compiler never "sees" the original invocation. Again, this is most effective when dealing with small functions.
Is there a difference? Yes and no. The two methods can result in the exact same object code, but (with macros) you lose type checking and other checking of various "problems", such as side effects, that can cause your code to work in an unexpected fashion. THese side effects can be difficult to diagnose with macros, because you don't directly see what is actually being compiled. The down side of both methods is that you have duplicate code in each place. The up side is speed.
The inline attribute is a compiler "hint". The compiler can choose to ignore it. By letting the compiler choose, you can gain performance and/or code size benefits, so it is better to go with inlining - that way, the compiler can catch problems before they become difficult to solve.
How do you install boost c plus plus library?
Follow the instructions provided by the official Boost website (see related links below):
InstallationTo install Boost.Build from an official release or a nightly build, as available on the official web site, follow these steps:If you are not using a Boost.Build package, but rather the version bundled with the Boost C++ Libraries, the above commands should be run in the tools/build/v2 directory.
Now that Boost.Build is installed, you can try some of the examples. Copy PREFIX/share/boost-build/examples/hello to a different directory, then change to that directory and run: PREFIX/bin/b2
A simple executable should be built.
A null pointer exception in java comes when you are trying to perform any action on an object that isnt initialized/has a value i.e., is a NULL Value
Ex:
private String s; //declare a string
if(s.equals("test")){
//do something..
}
You will get a null pointer in the if condition because you are checking a value that is null which is not allowed..
Write a program to illustrate bitwise operators without swap?
#include<stdio.h> int main() { int n,n2; printf("enter the no. < 15 "); // here i am considering the case of 4 bits. (1111) binary = (15) decimal scanf("%d",&n); n2=n^10; /* 10 = 1010 in binary form, to invert its even bits , we will use bit wise XOR (^) operator 1010 has 1 at its even places, so it will invert the even bits of n. if there is any further problem mail me at buntyhariom@gmail.com www.campusmaniac.com */ printf("\n%d",n2); return 0; }
What are entities in c plus plus?
Entities are the objects instantiated by your program, both at compile time and at runtime. Some objects are primitive data types, others are more complex such as objects instantiated from a class.
What is the object used to print information on the screen in C plus plus?
You are probably referring to the global std::cout object, however std::cout does not put information on a screen, it puts information into the standard console output device which can be redirected to any output device the user chooses (the screen, a file, a line-printer, the nul device, etc).
Difference between pop and push operation in data structure through c?
Pushing means putting an item onto a stack (data structure), so that it becomes the stack's top-most item. Popping means removing the top-most item from a stack. (You often hear a third term, peeking, which means looking at/reading the top-most item.)
When it comes to queues, you should generally use the terms enqueueing and dequeueing instead, where the former means appending an item to a queue's "back end" and the latter means removing the item at the "front end" from the queue.
These definitions suggest that a stack (if you picture it in your head) is spatially vertical, while a queue is horizontal. Another difference is that operations on a stack always happen at the same end, while operations on a queue happen at opposite ends.
When it comes to linked lists and double-ended queues (deques), the terms push and pop are also used, e.g. in C++'s STL, where you have operations such as push_front, push_back, pop_front, and pop_back. These simply imply that items can be appended or removed at both ends.
How mobile number validation is done in C programming?
It depends what you mean by validation. If you mean the actual phone number itself, the best you can do is count the digits to ensure it is the correct length. But that will only tell that it could be a phone number, not that it is a phone number. You'd have to dial the number to check its actual validity.
If you actually mean the 15-digit IMEI number, that can be easily validated. The final digit (#15) is a checksum digit. To validate the IMEI, double every second digit. If the product is greater than 10, subtract 9 (same as adding the two digits together). Finally add all 15 digits together. If the sum is divisible by 10, the number is a valid IMEI number. An example implementation is shown:
#include
int main()
{
int IMEI[15];
int i = 0;
int sum = 0;
char cIMEI[16];
memset( &cIMEI[0], 0, 16 );
while( strlen( cIMEI ) != 15 )
{
std::cout << "Enter the 15-digit IMEI number: ";
std::cin.getline( cIMEI, 16, '\n' );
}
// Convert characters to integers (digits).
for( i=0; i<15; ++i)
IMEI[i] = (int) ( cIMEI[i] - '0');
// Iterate the digits.
for( i=0; i<15; ++i)
{
// For odd elements only (every 2nd digit).
if( i % 2 )
{
IMEI[i] *= 2; // Double the digit.
if( IMEI[i] > 9 ) // Is the product 10, 12, 14, 16 or 18?
IMEI[i] -= 9; // Add the 2 individual digits together.
}
// Update the sum.
sum += IMEI[i];
}
// Display the result:
std::cout << "The IMEI number is ";
if( sum % 10)
std::cout << "invalid!" << std::endl;
else
std::cout << "valid!" << std::endl;
return( 0 );
}
With the help of a program explain the depth first traversal of a tree?
Refer to the following code and example output below.
#include<iostream>
#include<time.h>
#include<queue>
#include<stack>
class tree
{
private:
struct node
{
static unsigned s_id; // static id
unsigned id; // instance id
unsigned data; // instance data
unsigned depth; // depth of node
node* left; // pointer to left node (may be NULL)
node* right; // pointer to right node (may be NULL)
node (unsigned num, unsigned depth): data (num), left (NULL), right (NULL), id (s_id++), depth (depth) {}
~node () { delete (left); delete (right); }
void insert (unsigned num)
{
if (num < data)
{
if (!left)
left = new node (num, depth+1);
else
left->insert (num);
}
else
{
if (!right)
right = new node (num, depth+1);
else
right->insert (num);
}
}
void print ()
{
std::cout<<"ID: "<<id<<" Depth: "<<depth<<" Data: "<<data<<std::endl;
}
void print_sorted ()
{
if (left)
left->print_sorted ();
print();
if (right)
right->print_sorted ();
}
};
node* m_root;
public:
tree (): m_root (NULL) {}
~tree (){ delete (m_root); }
void insert (unsigned num)
{
if (!m_root)
m_root = new node (num, 0);
else
m_root->insert (num);
}
void print_sorted ()
{
std::cout<<"Sorted-order traversal\n"<<std::endl;
if (m_root)
{
m_root->print_sorted ();
std::cout<<std::endl;
}
}
void print_breadth_first ()
{
std::cout<<"Breadth-first traversal\n"<<std::endl;
std::queue<node*> q;
if (m_root)
{
// enque the root
q.push (m_root);
// repeat while the queue is not empty
while (!q.empty ())
{
// dequeue the first node
node* n = q.front ();
q.pop ();
// report the node
n->print ();
// enqueue left and right nodes
if (n->left)
q.push (n->left);
if (n->right)
q.push (n->right);
}
std::cout<<std::endl;
}
else
std::cout<<"The tree is empty!\n"<<std::endl;
}
void print_depth_first ()
{
std::cout<<"Depth-first traversal\n"<<std::endl;
std::stack<node*> s;
if (m_root)
{
// stack the root
s.push (m_root);
// repeat while the stack is not empty
while (!s.empty())
{
// unstack the top node
node* n = s.top ();
s.pop ();
// report the node
n->print ();
// stack left and right nodes
if (n->right)
s.push (n->right);
if (n->left)
s.push (n->left);
}
std::cout<<std::endl;
}
else
std::cout<<"The tree is empty!\n"<<std::endl;
}
};
// initialise static data
unsigned tree::node::s_id = 0;
int main()
{
srand((unsigned) time(NULL));
// create tree with 10 random numbers
tree t;
for(unsigned i=0; i<10; ++i)
t.insert (rand ());
t.print_sorted ();
t.print_breadth_first ();
t.print_depth_first ();
}
Example output:
Sorted-order traversal
ID: 6 Depth: 2 Data: 334
ID: 4 Depth: 1 Data: 2335
ID: 0 Depth: 0 Data: 12490
ID: 5 Depth: 4 Data: 15590
ID: 9 Depth: 5 Data: 18484
ID: 3 Depth: 3 Data: 23160
ID: 2 Depth: 2 Data: 23786
ID: 8 Depth: 3 Data: 24171
ID: 1 Depth: 1 Data: 24598
ID: 7 Depth: 2 Data: 30731
Breadth-first traversal
ID: 0 Depth: 0 Data: 12490
ID: 4 Depth: 1 Data: 2335
ID: 1 Depth: 1 Data: 24598
ID: 6 Depth: 2 Data: 334
ID: 2 Depth: 2 Data: 23786
ID: 7 Depth: 2 Data: 30731
ID: 3 Depth: 3 Data: 23160
ID: 8 Depth: 3 Data: 24171
ID: 5 Depth: 4 Data: 15590
ID: 9 Depth: 5 Data: 18484
Depth-first traversal
ID: 0 Depth: 0 Data: 12490
ID: 4 Depth: 1 Data: 2335
ID: 6 Depth: 2 Data: 334
ID: 1 Depth: 1 Data: 24598
ID: 2 Depth: 2 Data: 23786
ID: 3 Depth: 3 Data: 23160
ID: 5 Depth: 4 Data: 15590
ID: 9 Depth: 5 Data: 18484
ID: 8 Depth: 3 Data: 24171
ID: 7 Depth: 2 Data: 30731
Each node reports its ID, depth and data. The ID tells us the sequence the nodes were created, where the node with ID 0 is always the root. The depth tells us the level within the tree where the node exists, such that the root is on level 0. With this information it is possible to draw a graph of the tree and thus better understand the order in which nodes are processed.
The first listing shows the nodes in ascending order by data. With binary search trees this is the normal method of traversal.
The second listing shows a breadth-first traversal, where each level is processed in turn, from left to right.
The final listing shows a depth-first traversal where we follow left nodes before right nodes.
You will notice that the implementation of breadth-first and depth-first are fairly similar, the only real difference being that breadth-first employs a queue while depth-first employs a stack. The nature of a stack also means we must push right nodes before left nodes to ensure left nodes are processed before right nodes.
At first glance there doesn't appear to be much merit in either breadth-first or depth-first traversal. However, the example merely serves to show the difference between all the methods of traversal. When considering more complex graphs or maps, it may be advantageous to search through all the vertices that form an edge with a particular vertex (breadth-first) or to examine all the edges between one vertex and another vertex, where several routes might be available (depth-first). Both depth-first and breadth-first have practical applications in network routing and satellite navigation, where maps and charts must be graphed and traversed in a more logical manner than would otherwise be possible with sorted-order traversal.
How do you get Thiruvalluvar University BCA questions for OOP in c plus plus?
Your best bet would be to contact the university directly.
How to handle derived class exception in c plus plus?
Before we look at how to handle an exception in a derived class, it is important that you understand what happens when an exception is thrown. As soon as an exception is thrown, the call stack immediately unwinds until a suitable handler for the exception is found. If no handler is found and the call stack is completely unwound back to the main function, the application terminates with an unhandled exception.
By way of an example, consider the following:
#include<iostream>
#include<exception>
#include<memory>
struct A {
A () { std::cout << "Construct\tA\n"; }
~A () { std::cout << "Destruct\tA\n"; }
virtual void do_something(int i) = 0;
};
struct B : A {
B () { std::cout << "Construct\tB\n"; }
~B () { std::cout << "Destruct\tB\n"; }
void do_something(int i) override;
};
void B::do_something (int i)
{
std::cout << "Begin B::do_something(" << i << ")\n"; if (!i)
throw std::range_error ("B::do_something(int) : argument must be non-zero!");
std::cout << "End B::do_something(" << i << ")\n";
}
void caller()
{
std::cout << "Begin caller()\n";
B* b = new B;
for (int i=-5; i<=5; ++i)
b->do_something (i);
delete b;
std::cout << "End caller()\n";
}
int main()
{
std::cout << "Begin main()\n";
caller();
std::cout << "End main()\n";
}
When you execute this code, you will see the following output:
Begin main()
Begin caller()
Construct A
Construct B
Begin B::do_something(-5)
End B::do_something(-5)
Begin B::do_something(-4)
End B::do_something(-4)
Begin B::do_something(-3)
End B::do_something(-3)
Begin B::do_something(-2)
End B::do_something(-2)
Begin B::do_something(-1)
End B::do_something(-1)
Begin B::do_something(0)
The program terminates at this point with an unhandled exception. The trace code obviously gives us an idea of where the exception occurred however the purpose of the trace code is not to track down the problem, it is merely to highlight the flow of execution (in real code we may not have access to any trace code at all).
If we place a catch-all exception handler in main(), we can get a better idea of what the problem is:
int main()
{
std::cout << "Begin main()\n";
try
{
caller();
}
catch (...) // catch-all
{
try
{
std::exception_ptr eptr = std::current_exception();
std::rethrow_exception (eptr);
}
catch (const std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
std::cout << "End main()\n";
}
Note the use of a nested try-catch in the catch-all. This is required because we have no way of knowing what type of exception we're actually dealing with in the catch-all. We first obtain an exception pointer to the current exception and then re-throw that pointer. This creates a standard exception which we can catch and handle normally.
Now we get the following output:
Begin main()
Begin caller()
Construct A
Construct B
Begin B::do_something(-5)
End B::do_something(-5)
Begin B::do_something(-4)
End B::do_something(-4)
Begin B::do_something(-3)
End B::do_something(-3)
Begin B::do_something(-2)
End B::do_something(-2)
Begin B::do_something(-1)
End B::do_something(-1)
Begin B::do_something(0)
Exception: B::do_something(int) : argument must be non-zero!
End main()
The program appears to exit normally so you might think that we could feasibly keep this program running now that we've handled the exception. But we cannot. We haven't actually handled the exception at all we've simply logged the problem at this stage.
From the trace output we can see that derived object B was constructed, but it was not destroyed. More importantly, the pointer we used to construct that object no longer exists: it was local to the caller() function and that fell from scope the moment we entered the catch-all in main(). The pointer is gone but the B object it pointed to still exists in memory (as does its base class A). in other words, we've created a resource leak.
If nothing else, this example should demonstrate quite clearly why we must never use raw pointers to dynamically allocated memory in C++. Even though we have a catch-all in main(), we have no way to recover resources allocated between main() and the point at which the exception was thrown, so the only option is to exit the program at this point.
The best way to avoid leaked resources is to use a resource handle instead of raw pointers. That is, if we use a statically-allocated object that encapsulates a raw pointer, we get the benefit of dynamic allocation and automatic recovery in the event of an exception. Consider the following alternative implementation of our caller() function:
void caller()
{
std::cout << "Begin caller()\n";
std::unique_ptr<B> b {new B};
for (int i=-5; i<=5; ++i)
b->do_something (i);
std::cout << "End caller()\n";
}
The std::unique_ptr class is a smart pointer. It behaves just like a raw pointer but we no longer need to explicitly delete the pointer; the smart pointer does that for us automatically as soon as it falls from scope. Indeed, if we try to explicitly delete a smart pointer, we'd get a compiler error. Remember that a smart pointer is not a pointer at all, it just behaves like one.
If we run the program again, we see the following output:
Begin main()
Begin caller()
Construct A
Construct B
Begin B::do_something(-5)
End B::do_something(-5)
Begin B::do_something(-4)
End B::do_something(-4)
Begin B::do_something(-3)
End B::do_something(-3)
Begin B::do_something(-2)
End B::do_something(-2)
Begin B::do_something(-1)
End B::do_something(-1)
Begin B::do_something(0)
Destruct B
Destruct A
Exception: B::do_something(int) : argument must be non-zero!
End main()
As you can see, our B object now destroys itself automatically (along with the base class A). Now we're in a better position to make a full recovery from the exception and deal with it properly.
Can you give an example Main function in Cpp?
The main function is the entry point of your application. The minimal main() function is as follows:
int main()
{
return( 0 );
}
Clearly this does nothing but return the value zero to the caller. However, it is important to note that the main() function must return an integer to the calling program -- even if only zero. The return value may be used to indicate an error condition, with zero indicating success, but can be used for any purpose -- or it may be ignored altogether by the caller. However it is not for you to decide how the return value is used, so long as you return something. A main() function that returns void is an invalid program (some compilers may permit it, but they break the C/C++ standard if they do).
An actual main() function will normally include one or more sequential statements or function calls, or an infinite loop with a conditional expression to exit the loop. An infinite loop may be contained in another function. The loop may be used to process a message queue, for instance, which determines the program's flow of control.
The following example demonstrates a simple program containing infinite loop within main() itself, generating random numbers between 1 and 100 (inclusive), exiting the loop when the number is 1. The return value is the number of loops that were executed.
#include
#include
int main()
{
srand(( unsigned ) time( NULL ));
unsigned int loops = 0;
while( ++loops )
{
int n = rand() % 100 + 1;
std::cout << "Number: " << n << std::endl;
if( n == 1 ) break; // exit loop if n is 1.
}
std::cout << "Loops: " << loops << std::endl;
return( loops ); // return number of loops to caller.
}
int array[10] = {...};
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) array[i] += 5;
else array[i] -= 10;
}
What is swap pointing c plus plus?
// Swap Pointer
// Demonstrates passing constant pointers to alter argument variables
#include
<iostream>
using
namespace std;
void
badSwap(int x, int y);
void
goodSwap(int* const pX, int* const pY);
int
main()
{
int myScore = 150;
int yourScore = 1000;
cout <<
"Original values\n";
cout <<
"myScore: " << myScore << "\n";
cout <<
"yourScore: " << yourScore << "\n\n";
cout <<
"Calling badSwap()\n";
badSwap(myScore, yourScore);
cout <<
"myScore: " << myScore << "\n";
cout <<
"yourScore: " << yourScore << "\n\n";
cout <<
"Calling goodSwap()\n";
goodSwap(&myScore, &yourScore);
cout <<
"myScore: " << myScore << "\n";
cout <<
"yourScore: " << yourScore << "\n";
return 0;
}
void
badSwap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
void
goodSwap(int* const pX, int* const pY)
{
//store value pointed to by pX in temp
int temp = *pX;
//store value pointed to by pY in address pointed to by pX
*
pX = *pY;
//store value originally pointed to by pX in address pointed to by pY
*
pY = temp;
}