answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

How do you solve this game show program in Linux by C plus plus language?

this the question:

Write a program that will simulate the following situation 10,000 times so we can decide the answer to:

Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which he knows has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?

The pseudocode for this assignment would be:

Run a loop 10,000 times that:

  • Randomly picks a door that is the "prize door"
  • Randomly picks a door that is the "first choice"
  • Removes one of the doors that is both not the "prize door" nor the "first choice"
  • Randomly picks one of the remaining doors as your "second choice"
  • Compares the "prize door" to the "first choice" and "second choice" and saves it

After the loop is done, output a message that tells how many times the "prize door" was the "first choice" and how many times the "prize door" was the "second choice" so we can know what is the best choice.

The output of the homework should look like:

Number of times staying was the correct strategy: [NUMBER]

Number of times switching was the correct strategy: [NUMBER]

Therefore, the best thing to do is to [STRATEGY].

Would you Write c plus plus program using array for Fibonacci number?

You can write a C++ fib pro using arrays but the problem is the prog becomes very complicated since u need to pass the next adding value in an array.....

Write a program for a matchstick game being played between the computer and a user What if your program should ensure that the computer always wins using c plus plus?

The following example demonstrates a simple implementation using 15 matches where you take turns removing 1, 2 or 3 matches. The player who removes the last match loses.

In order to ensure the computer always wins, the computer must always play first. In the example, the player always starts but unless the player knows the secret, the computer will always win.

#include<iostream>

#include<conio.h>

unsigned ask(unsigned max=3)

{

int choice = 0;

do

{

choice = getch() - '0';

if (choice<0 choice>max)

choice=0;

else

{

std::cout<<choice<<'\n'<<std::endl;

break;

}

} while (!choice);

return ((unsigned)choice);

}

bool yn()

{

int choice = 0;

bool result = false;

while(1)

{

choice = getch();

if (choice=='y' choice=='Y')

{

result = true;

break;

}

if (choice=='n' choice=='N')

{

result = false;

break;

}

}

std::cout<<(char)choice<<'\n'<<std::endl;

return (result);

}

int main()

{

unsigned start = 15;

unsigned matches = start;

bool player = true; // set to false so computer always starts

unsigned take = 0;

while (1)

{

std::cout<<"There "<<(matches==1?"is":"are")<<" "<<matches<<" match"<<(matches==1?"":"es")<<" remaining.\n"<<std::endl;

if( matches <= 1 )

{

if ((player && matches == 1) (!player && !matches))

std::cout<<"You lose!\n"<<std::endl;

else

std::cout<<"You win!\n"<<std::endl;

std::cout<<"Would you like to play again? ";

if (!yn())

break;

else

{

matches = start;

continue;

}

}

if( player ) // player's turn

{

std::cout<<"Would you like to take 1";

if( matches>2 )

{

std::cout<<", 2 or 3 matches? ";

take = ask( 3 );

}

else

{

std::cout<<"or 2 matches? ";

take = ask( 2 );

}

}

else // computer's turn

{

take = (matches-1)%4;

if( !take )

take = rand()%3+1;

std::cout<<"I will take "<<take<<" matches.\n"<<std::endl;

}

matches -= take;

player = !player; // toggle player

}

}

What type of scenario would you use a data queue?

Whenever you need to buffer sequential data for processing in a first in, first out manner. In a multi-processing, multi-threaded environment, incoming data may be received at any time. If the function that processes that data is otherwise occupied with a datum, the new data needs to be buffered until the function is ready to deal with it, thus the data is placed in a queue.

In Windows, for instance, an application's message queue exists to buffer incoming system messages until the application's message loop is ready to deal with them. If a process is running in the same thread as the message loop, the message loop cannot process any messages in the queue until that process terminates or yields control. This is why time-intensive functions must always periodically yield control to the system to allow pending messages to be processed. If the function does not yield control, the application (and often the system itself) can appear to be completely unresponsive, making the user think the system is "hung, when it is in fact doing exactly what you told it to do.

What is a Pure Virtual Function Write a C plus plus program using Pure Virtual Function?

A pure-virtual method is similar to a virtual method. A virtual method is a method that is expected to be overridden in a derived class while a pure-virtual method must be overridden in a derived class. The base class may provide a default implementation for a pure-virtual method, but it is not a requirement, whereas it must provide an implementation for a virtual method. In addition,

any base class that has a pure-virtual method becomes abstract; you cannot instantiate abstract classes -- you are expectedto derive from them.

#include

class Abstract

{

public:

// Pure-virtual method; note the '=0' to denote pure-virtual.

virtual void Show()=0;

};

class Derived : public Abstract

{

public:

virtual void Show()

{

// Implementation is required here!

std:: cout << "Derived" << std::end;

}

};

void main()

{

// Abstract a; // Compiler error!

Derived d;

d.Show(); // Call pure-virtual method.

return( 0 );

}

Composite numbers from 1-10 in c plus plus programming?

#include<iostream>

bool is_composite (const size_t);

bool is_prime (const size_t);

int main()

{

for (size_t num=1; num<=10; ++num)

if (is_composite (num))

std::cout << num << " is composite\n";

}

bool is_composite (const size_t num)

{

if (num < 4U)

return false;

return !is_prime (num);

}

bool is_prime (const size_t num)

{

const size_t two = 2U;

if (num < two)

return false;

if (!(num % two))

return num == two;

const size_t max = static_cast<size_t>(sqrt (static_cast<double>(num)));

for (size_t div = 3U; div <= max; div += two)

if (!(num % div))

return false;

return true;

}

Write c plus plus program that input are integer an array consisted of 4 elements than array it's elements in asceding order and print it?

#include<iostream>

#include<sstream>

using namespace std;

int main()

{

std::vector<int> input;

for (size_t index=0; index<4; ++index)

{

cout << "Enter a number: ";

bool valid=false;

while (!valid)

{

string in;

cin >> in;

stringstream ss;

ss << in;

if (!(valid = (ss >> input[loop]))

std::cout << "Invalid input! Try again: ";

}

}

std::cout << "\n\nYou entered the following: ";

for (size_t index=0; index<4; ++index)

cout << input[loop] << ' ';

cout << '\n' << endl;

}

Does windows XP supports the turbo c plus plus graphics?

You should actually turn the question around: does the Turbo C++ graphics library support Windows XP? The answer is yes it does, provided you are using a version of Turbo C++ for Windows XP and above.

Why Cin and Cout cannot be used outside the main function?

You are completely wrong here.

Another answer:

There is nothing to say you cannot use cin or coutoutside the main() function (for example, you can use them in a function called from main()). However, using them before main() has been called (e.g. in the constructor of a static object) can have disastrous consequences: cin and cout are themselves static objects, and static initialisation order is undefined. Thus you could be calling them before they have been properly constructed.

Where do c plus plus begin execution?

C++ begins its execution at int main(...parameters...) or int WINAPI WinMain(...parameters...). WinMain() is used in Win32 programming, for windows, message boxes etc. main() is used in console programming.

int main() either have no parameters ( int main()) or it can have two parameters ( int main(int argc, const char* argv[]) ). int argc is the argument count, and const char* argv[] is the argument vector (the values of the arguments). These parameters are only useful if you need to take arguments from the user when you start up the application.

int WINAPI WinMain() must have four parameters. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdParam, int nCmdShow). WINAPI is a method of passing parameters which comes from the days of Fortran and Pascal. It reverses the order the parameters are passed. Why this is necessary is not important WINAPI is simply required by Windows. HINSTANCE hInstance is a handle (a pointer) to the current application instance. HINSTANCE hPrevInstance is a handle to the previous instance. In theory, if there are multiple copies of an application open, then this would point to the last one created. LPSTR lpCmdParam is a long pointer to the command line calling existence to the application. If you were to open, let's say, "MyWin32App.exe" then this would be what lpCmdParam is pointing to. If you were to open "MyWin32App.exe -StartFullscreen" then that would be what it is pointing to. int nCmdShow is the parameter indicating how the window should be opened. You could start the application minimised, maximised etc.

References:

http://www.directxtutorial.com/Tutorial9/A-Win32/dx9A2.aspx

http://en.wikipedia.org/wiki/Main_function_(programming)#C_and_C.2B.2B

What is a virtual base class in C plus plus when the different methods in base and derived classes have the same name true or false?

False. A virtual base class is one that is common to two or more derived classes that are themselves base classes, and that may be combined through multiple inheritance. By declaring the common base class to be virtual in its direct derivatives, only one instance of the common base class exists in the multiple-inheritance classes.

What is the C plus plus program for quick sort using template function?

#include<iostream>

#include<time.h> // used by srand()

// Swap the given values (by reference).

template<class T>

void exch( T& x, T& y )

{

T tmp=x;

x=y;

y=tmp;

}

// Generates a pseudo-random number in the range min to max (inclusive).

int get_rand( const int range_min=0, const int range_max=RAND_MAX )

{

static bool seeded = false;

if( !seeded )

{

seeded = !seeded;

std::srand((unsigned) time(NULL));

while( get_rand() );

}

return((int)((double)std::rand() / (RAND_MAX+1) * ((range_max+1) - range_min) + range_min));

}

template<class T>

void quicksort( T a[], int l, int r )

{

int i;

static int j;

tail_call:

if(r<=l)

return;

// Select random pivot and move it to end of array.

exch( a[get_rand(l,r)], a[r] );

i = l-1;

j = r;

while(1)

{

// Locate the 1st value from left that is not less than the pivot.

while(a[++i]<a[r]);

// Locate the 1st value from right

while(a[r]<a[--j])

if(j==l)

break;

if(i>=j)

break;

exch(a[i], a[j]);

}

exch( a[i], a[r] );

// Determine the smaller subset

static int l1, l2;

l1=l, l2=i-1;

int r1=i+1, r2=r;

if(r2-r1<l2-l1)

{

l1=r1, l2=r2;

r1=l, r2=i-1;

}

// Recurse over smaller subset

quicksort( a, l1, l2);

// Tail-call over largest subset

l=r1, r=r2;

goto tail_call;

}

// Helper method: sorts an array up to the given size.

template<class T>

void quicksort( T a[], const size_t size )

{

if( size < 2 )

return;

quicksort( a, 0, size-1 );

}

template<class T>

void print_array(T a[], const size_t size)

{

for(int i=0; i<size; ++i)

std::cout<<my_array[i]<<" ";

std::cout<<'\n'<<std::endl;

}

int main()

{

size_t size=1000000;

int my_array[size];

for( int i=0; i<size; ++i )

my_array[i]=get_rand( 1, size );

print_array( my_array, size );

std::cout<<"Sorting...\n"<<std::endl;

quicksort(a,size);

print_array( my_array, size );

}

What to do to change c to c plus plus in turbo c plus plus?

The first thing to do is wrap the C code so the compiler knows to treat it specifically as C rather than C++:

// Include directives go here.

#ifdef __cplusplus

extern "C" {

#endif // __cplusplus

// C code goes here.

#ifdef __cplusplus

}

#endif // __cplusplus

Often that's all you need to do. However, be aware that C++ uses reserved keywords that C does not not know anything about, so if you have C variables named "this" or "class" or "virtual", etc, then you must rename them throughout the C code.

C does not adhere to the strict type-safety in C++. Therefore all calls to malloc (which returns void*) need to be cast to the specific type. Also, be wary of implicit casts from int to enum. C++ does not support this, but C does.

Also be aware of sizeof() differences. In C, sizeof(char) typically returns 4 (bytes), whereas in C++ it always returns 1 (byte).

How does one implement the Huffman tree algorithm in c plus plus?

As a student in 1951, David A. Huffman (1925-1999) was given the option of sitting a final exam or submitting a term paper. He chose the latter. The term paper outlined the problem: find the most efficient binary code. In other words, given any amount of data, find the most efficient method of encoding that data in the least number of bits. When we encode data using standard 8-bit symbols, every symbol is obviously the same length (8 bits). If we alter the encoding so that we use shorter codes for symbols that appear most often, and longer codes for those that appear less often, we can encode the data more efficiently. For instance, if the most frequent symbol could be encoded with just 1 bit (say, 0), then we save 7 bits for every occurrence of that symbol. However, no other symbol can use an encoding that begins with 0, they must all be longer than 1 bit and must begin with a 1. Moreover, no symbol can start with the same sequence of bits assigned to any other symbol.

Huffman quickly ascertained that he was looking for a prefix coding method. While efficient encoding methods certainly existed at the time (Shannon-Fano being one), none could be guaranteed to provide the most efficient coding. Indeed, Huffman had all but given up and resigned himself to the final exam when the answer finally dawned on him. If he used a frequency-sorted binary tree, he could encode any symbol in the tree by tracing the path back to the root. The symbols formed the leaves of the tree and if he followed the left path to the leaf's parent, he prefixed a 0 bit, otherwise he prefixed a 1 bit. Repeating this process all the way to the root, every symbol could be assigned a unique prefix code. Moreover, when reading the encoded data back, he simply started at the root and followed the left or right paths according to the bits in the prefix. When he reached a leaf node, he'd found his symbol, and started at the root to find the next.

Huffman wasn't the first to discover this of course, but what had eluded all the mathematicians and programmers of the day was simply how to go about building the tree in the first place. Normally we build trees from the top down, from the root. Huffman's revelation was in building the tree from the bottom up, starting with the leaves. With this simple change, not only did he complete his term paper with honours, he exceeded even his professor's expectations. His method proved to be the most efficient encoding and Huffman's name was entered into the computing history books.

Huffman started by creating a frequency table of symbols which he then sorted in descending order of frequency. He then copied the table and, while the copy contained more than one node, he extracted (removed) the last two nodes and constructed a parent node, with the last node attached to its left node, and its predecessor to its right. The parent node's frequency was the sum of its left and right node frequencies. The parent node was then inserted back into the copy, maintaining the descending order of frequency. When only one node remained in the copy, the tree was complete. The one remaining node becomes the root of the Huffman tree.

You then encode the tree. Initially, all nodes have no prefix code but, starting from the root, you copy its prefix (an empty string) to its left child and append a "0", and then recursively encode the left child (thus its left child will be prefix "00"). Do the same for the right child, but append a "1" instead. Thus the child to the right of the root's left child will be prefix "01". When you reach a leaf, its prefix code determines the precise route you took from the root to the leaf (where "0" means go left, and "1" means go right). Since the tree was a copy of the frequency table, each leaf in the original frequency table will also be encoded.

You are now ready to begin encoding the file. You begin by outputing the original file size (so you know when to stop reading when decoding the encoded file). You then output the binary representation of the tree and its symbols. That is, starting from the root node, output a 0 bit if it is a parent node, or a 1 bit followed by the 8-bit unencoded symbol if it is a leaf. Repeat the process for the node's left and right children if it has any (it must have both or neither, it cannot have one but not the other). Finally, read the original file one symbol at a time, locate it in the frequency table, and output its prefix code. When writing individual bits, you need to use a bitwriter that buffers up to 8 bits at a time and then write a complete byte. When you write the final bit, pad any unused bits with zeroes to make a full byte.

To decode the encoded file, use a bitreader to read back 1 bit at a time. Decoding is simply a matter of reading the file size, then reconstructing the tree from its binary representation, and then reading one bit a time to navigate the tree from the root. when you reach a leaf, output the symbol, decrement the file size and return to the root. Repeat until the file size is zero, at which point the original file is restored.

The following implementation is not complete by any means. For instance, if you were to encode a file containing the text "The quick brown fox jumps over the lazy dog.", you will find that this 44 byte file compresses to a 66 byte file. This seems unimpressive, but remember that the encoded file also contains the file size and the Huffman tree as well as the encoded data. The encoded data is actually smaller than the original file, but because the file is so small to begin with, the overhead of the additional information produces a larger file. Huffman encoding works best on larger files (the bigger the better). An alternative approach is to use a static table, thus eliminating the need to transmit the table along with the encoded data. However this only works when the frequency table is highly predictable -- it won't be suitable for all file types. Another approach is to create several static tables, and use the one that produces the smallest file. Again, this is less than optimal, but if you have 255 different tables, then you only need to transmit 8 additional bits to determine which table to use for decoding (where table 0 implies no encoding, for those files that cannot be reduced with any of the tables). But for larger files, the overhead of the frequency table is more than outweighed by the reduction in the encoded data. For instance, a file that contains nothing but 0 bits can be reduced to a file a little over 1/8th the size of the original file. Of course, such a file could easily be compressed to a fraction of that simply by utilising run length encoding, but you can also combine both methods, using RLE to reduce the repeated bit sequences, and then Huffman encoding to reduce the RLE file. These implementations (amongst many others, many of which are patented) are left for the reader to discover.

In the meantime, be aware that the following implementation provides only the minimum functionality to both encode and decode using Huffman's algorithm, and makes use of standard output for the DESTINATION file (you may wish to make the destination file a command-line option, and test the source and destination are actually different files). Note also that besides some simple error-checks (some of which are unnecessary with prudent assertions and verifications), overall robustness has been sacrificed for the sake of simplicity.

// Huffman.exe

// Copyright ©2013 PCForrest.

#include<iostream>

#include<list>

// The bitreader class facilitates the reading

// of binary files, 1 bit at a time.

class bitreader

{

public:

// The constructor accepts a file pointer to a file that is

// already opened for binary reading. The m_size and m_buffer

// members are initially zero.

bitreader( FILE* file ): m_file( file ), m_buffer( 0 ), m_size( 0 ){}

~bitreader(){};

int readbit();

public:

FILE* m_file;

unsigned char m_buffer;

int m_size;

};

// Returns a single bit (0 or 1) from the file.

// Returns -1 if an error occurs.

int bitreader::readbit()

{

// Are there any bits in the buffer?

if( !m_size )

{

// Read 8 bits into the buffer.

size_t read = fread( &m_buffer, 1, 1, m_file );

if( read == 1 )

m_size = 8;

else

// Fatal error!

return( -1 );

}

// If we get this far, there is at least 1 bit in the buffer.

// Extract the MSB from the buffer, shift the remaining bits

// left and decrement the size.

int bit = m_buffer&0x80?1:0;

m_buffer<<=1;

--m_size;

// Return the extracted bit.

return( bit );

}

// The bitwriter class facilitates the writing

// of binary files, 1 bit at a time.

class bitwriter

{

public:

// The constructor simply initialises the members.

bitwriter(): m_buffer( 0 ), m_unused_bits( 8 ){}

~bitwriter();

void writebit( unsigned char bit = 1 );

public:

char m_buffer; // The bit buffer.

int m_unused_bits; // Unused bits.

};

// The destructor pads any unwritten bits to make a full byte.

bitwriter::~bitwriter()

{

while( m_unused_bits != 8 )

writebit( 0 );

}

// Writes a single bit to the buffer. When the buffer is full,

// outputs the buffer to standard output and resets the buffer.

void bitwriter::writebit( unsigned char bit /* = 1 */ )

{

// Bit must be 0 or 1.

if( bit > 1 )

return;

// Decrement the buffer length.

--m_unused_bits;

if( bit )

{

// Shift the bit left if necessary.

if( m_unused_bits )

bit <<= m_unused_bits;

// Combine bit with current buffer.

m_buffer |= bit;

}

// Do we have a complete byte?

if( !m_unused_bits )

{

// Write the byte and empty the buffer.

std::cout << m_buffer;

m_buffer = 0;

m_unused_bits = 8;

}

}

// A node object acts as both a leaf and a parent. Only the

// leafs store any symbols. Parents store both a left and

// right node. During encoding, leafs store the frequency

// of their symbols while parents store the sum of the

// frequencies of their two children. During decoding,

// the frequency is not used.

class node

{

// Used when sorting the Huffman table.

friend bool compare(const node* x, const node* y);

public:

node( unsigned char data );

node( node& left, node& right );

~node( void );

int encode( bitwriter& writer );

int decode( bitreader& reader );

char get_symbol( void ) const { return( m_symbol ); }

unsigned int get_freq( void ) const { return( m_freq ); }

const std::string& get_code( void ) const { return( m_code ); }

node* get_left( void ) const { return( m_left ); }

node* get_right( void ) const { return( m_right ); }

void inc_freq( void ){ ++m_freq; }

private:

unsigned char m_symbol;

unsigned int m_freq;

std::string m_code;

node* m_left;

node* m_right;

};

// Constructs a leaf.

node::node( unsigned char symbol )

: m_symbol( symbol )

, m_freq( 1 )

, m_code( "" )

, m_left( NULL )

, m_right( NULL ) {}

// Constructs a parent.

node::node( node& left, node& right )

: m_symbol( 0 )

, m_freq( left.m_freq + right.m_freq )

, m_code( "" )

, m_left( &left )

, m_right( &right ){}

// Recursive destructor.

node::~node( void )

{

delete( m_left );

delete( m_right );

}

// Recursively decodes (rebuilds) the tree from the given bit reader.

int node::decode( bitreader& reader )

{

// Read the next bit.

int result = reader.readbit();

switch( result )

{

case( -1 ): // Fatal error!

return( result );

case( 0 ): // This node is a parent.

// Instantiate the left node.

if( m_left = new node(0) )

{

// Decode the left node (recursively).

result = m_left->decode( reader );

// Ensure success (zero).

if( !result )

// Instantiate the right node.

if( m_right = new node(0) )

// Decode the right node (recursively).

result = m_right->decode( reader );

}

// Return the result.

return( result );

case( 1 ): // This node is a leaf.

// Read the next 8 bits and store the resultant symbol.

for( int i=0; i<8; ++i )

{

m_symbol<<=1;

result = reader.readbit();

if( result == -1 )

return( result );

m_symbol |= result;

}

}

// Success!

return( 0 );

}

// Encodes the Huffman tree. If this node is a parent,

// write a 0 bit, otherwise write a 1 bit followed by

// the 8-bit unencoded symbol.

int node::encode(bitwriter& writer )

{

int error=-1;

// Is this node a leaf?

if( !m_left && !m_right )

{

// Write a 1 bit.

writer.writebit(1);

// Store the symbol locally.

unsigned char symbol=m_symbol;

// Write each bit from the MSB to the LSB.

for(int i=0; i<8; ++i, symbol<<=1)

writer.writebit(symbol&0x80?1:0);

// Success!

error=0;

}

// Or is this node a parent?

else if( m_left && m_right )

{

// Write a zero bit.

writer.writebit(0);

// Copy this node's code to the left node

// and append a 0.

m_left->m_code = m_code;

m_left->m_code += "0";

// Recurse for the left node.

error = m_left->encode( writer );

if( !error )

{

// Copy this node's code to the right node

// and append a 1.

m_right->m_code = m_code;

m_right->m_code += "1";

// Recurse for the right node.

error = m_right->encode( writer );

}

}

return( error );

}

// Compare method used to sort the Huffman table

// in descending order of frequency.

bool compare( const node* x, const node* y )

{

return( x->m_freq>y->m_freq );

}

// Decodes the given file name and redirects the

// decoded data to standard output.

int decode( const char* filename )

{

// Open the input file for binary reading.

FILE* input = fopen( filename,"rb" );

if( !input )

{

std::cerr<<"File access error: "<<filename<<std::endl;

return( -1 );

}

// Instantiate a bit reader object.

bitreader reader( input );

int error = -1, bit=0;

// Determine the length of the decoded data.

unsigned int len=0;

for( int i=0; i<sizeof(unsigned int)*8; ++i )

{

len <<= 1;

bit = reader.readbit();

if( bit == -1 )

return( error );

len |= bit;

}

// Instantiate the Huffman tree root.

node root( 0 );

// Decode (rebuild) the tree.

root.decode( reader );

// Begin reading the encoded data until all symbols

// have been read.

while( len-- )

{

// Point to the root of the Huffman tree.

node* pnode = &root;

// Repeat while the current node is a parent node.

while( pnode->get_left() && pnode->get_right() )

{

// Read the next bit.

bit = reader.readbit();

if( bit == error )

// Fatal error!

return( error );

// Navigate right if the bit is set, otherwise navigate left.

pnode = bit?pnode->get_right():pnode->get_left();

}

// We've reached a leaf, output the data.

std::cout << pnode->get_symbol();

}

// Success!

fclose( input );

return(0);

}

// Encodes the given file name and redirects the encoded

// data to standard output.

int encode( const char* filename )

{

// Open the file for binary reading.

FILE* input=fopen( filename,"rb" );

if( !input )

{

std::cerr<<"File access error: "<<filename<<std::endl;

return(-1);

}

// Instantiate the Huffman frequency table.

std::list<node*> table;

// Some variables.

unsigned int len=0;

char symbol=0;

// Read one symbol at a time.

while( fread( &symbol, 1, 1, input ) == 1 )

{

// Increment the file length.

++len;

// Locate the symbol in the Huffman frequency table.

std::list<node*>::iterator it=table.begin();

while( it!=table.end() )

{

// Reference the node.

node& rnode = *(*it);

// Check for equality.

if( rnode.get_symbol() == symbol )

{

// Symbol found, increment its frequency.

rnode.inc_freq();

break;

}

++it;

}

// Was the symbol found?

if( it==table.end() )

{

// No -- create a new node for the symbol

// and add it to the table.

node* pnode = new node( symbol );

table.push_back( pnode );

}

}

if( ferror( input ))

{

fclose( input );

std::cerr << "File read error: " << filename << std::endl;

return( -1 );

}

// Sort the Huffman frequency table in descending order of frequency.

table.sort( compare );

// Instantiate the Huffman tree (copy the Huffman frequency table).

std::list<node*> tree( table );

// Repeat while the Huffman tree has more than one node.

while( tree.size() > 1 )

{

// Extract the last two nodes.

std::list<node*>::reverse_iterator rit = tree.rbegin();

node* left = *rit++;

node* right = *rit;

tree.pop_back();

tree.pop_back();

// Create a parent node for the two extracted nodes.

node* parent = new node( *left, *right );

// Add the parent node and resort the tree.

tree.push_back( parent );

tree.sort( compare );

}

// Instantiate a bit writer.

bitwriter writer;

// Write the file length (32 bits).

for(int i=0; i<sizeof( unsigned int )*8; ++i, len<<=1)

writer.writebit( len&0x80000000?1:0 );

// Reference the root node of the Huffman tree.

node& root = *( *tree.begin() );

// Recursively encode the Huffman tree (also

// encodes the Huffman frequency table, since

// both contain pointers to the same nodes).

root.encode(writer);

// Read symbols from the start of the input file.

fseek( input, 0, SEEK_SET );

while( fread( &symbol, 1, 1, input ) == 1 )

{

// Locate the symbol in the Huffman frequency table.

for(std::list<node*>::iterator it=table.begin(); it!=table.end(); ++it )

{

// Reference the current node.

node& rnode = *(*it);

if( rnode.get_symbol() == symbol )

{

// Write the symbol's code.

for(unsigned int i=0; i<rnode.get_code().size(); ++i)

writer.writebit( rnode.get_code().at(i)=='1'?1:0 );

break;

}

}

}

if( ferror( input ))

{

fclose( input );

std::cerr << "File read error: " << filename << std::endl;

return( -1 );

}

// Finished with the input file.

fclose(input);

// Success!

return(0);

}

// The main function handles the command line.

int main(int argc, char* argv[])

{

if(argc==3)

{

std::string option( argv[2] );

if( !option.compare("-d") !option.compare("-D") )

if( decode(argv[1] ))

std::cerr<<"The input file cannot be decoded.\n"<<std::endl;

else

return(0);

else if( !option.compare("-e") !option.compare("-E") )

if( encode(argv[1] ))

std::cerr<<"The input file could not be encoded.\n"<<std::endl;

else

return(0);

}

std::cerr<<"Usage:\n\n"

<<argv[0]<<" SOURCE -switch > DEST\n"

<<"\nWhere:\n\n"

<<"\tSOURCE\t- source file name\n"

<<"\tDEST\t- destination file name\n\n"

<<"Switch:\n\n"

<<"\td\t- decode\n"

<<"\te\t- encode\n"<<std::endl;

return(-1);

}

Swapping of two numbers using function overloading in c plus plus?

#include #include void swap(int &ix,int &iy); void swap(float &fx,float &fy); void swap(char &cx,char &cy); void main() { int ix,iy; float fx,fy; char cx,cy; clrscr(); cout<<"Enter 2 integers:"; cin>>ix>>iy; cout<<"Enter 2 floating point no:s:"; cin>>fx>>fy; cout<<"Enter 2 characters:"; cin>>cx>>cy; cout<<"\nIntegers:"; cout<<"\nix="<

What is expansion of mfc in c plus plus?

The term "expansion of MFC" is meaningless. Note that the Microsoft Foundation Classes (MFC) library has nothing to do with C++. The MFC is a library designed by Microsoft for use in Microsoft Visual C++.

What is meant by passing an argument as a pointer to an object?

In C++ we can pass arguments to functions in only two ways: by value or by reference. The method is decided by the signature of the function we call. The following examples demonstrate these signatures:

void byval (object val) {}

void byref (object& ref) {}

When we pass arguments to the byval function, we are passing the value of those arguments. Thus the formal argument, val, is always a copy of the actual argument we pass and any changes made to the formal argument are not reflected in the actual argument.

When we pass arguments to the byref function, we are passing the argument itself. Thus the formal argument, ref, is an alias for the actual argument we pass and any changes made to the formal argument are reflected in the actual argument.

To pass an argument by pointer, the formal argument must be a pointer of the same type as the actual argument (or any derivative of that type):

void byptr(object* ptr) {}

If we don't have an actual pointer variable to pass to the function, we must use the address-of operator to obtain an automatic pointer variable that we can pass:

object something;

byptr (&something);

If we don't do this, the compiler will search for a function signature that accepts a value or a reference and will completely ignore the pass by pointer signature., resulting in a compile-time error.

Passing by pointer is essentially an alternative method of passing by reference. However, when we pass by pointer we introduce an extra layer of indirection that we don't get when we pass by reference. This is because we are not actually passing by reference at all, we're passing by value. Pointers are variables that store memory addresses, thus whatever address we pass as the actual argument, that address becomes the value that is copied to the formal argument, ptr. However, because the formal argument and the actual argument both refer to the same object (because they both point to the same memory address), we are effectively passing that object by reference.

Passing by reference is always the preferred method of passing complex objects into functions, because copying complex objects is expensive. Imagine if the object represented a list containing 1 million nodes. That's 1 million copies for the nodes alone. However, we cannot pass by reference if there's even the slightest possibility there may be no object to pass. References cannot be NULL (or if they are, the program is deemed invalid) but pointers can be NULL. So in these cases we can pass by pointer rather than by reference.

Programmers try very hard never to pass function arguments more than 4 bytes in length (or 8 bytes on 64-bit systems). Thus passing primitive variables by value is fine unless you want changes reflected in the actual arguments. But complex objects must always be passed by reference, or by pointer variable, which is also a primitive type in itself because memory addresses are always the same length, depending on the architecture (32/64-bit).

Pointers can also be passed by reference as well as by value. Being able to pass a pointer by value means we can operate upon the object being pointed to, but we cannot change the value of the actual argument itself -- the pointer that was originally passed to the function. To do that we must pass the pointer by reference and we achieve this by introducing yet another layer of indirection, by passing a pointer to pointer variable:

void bypptr(object** pptr) {}

When we do this, pptr now holds the memory address of the pointer we actually passed, not the memory address of the object it pointed to. Thus we can change the memory address stored in that pointer thereby pointing it to another object of the same type, or indeed NULL, just as if we'd passed that pointer by reference.

Remember that pointers are just variables -- they simply store memory addresses. The pointer's type tells us what type of data resides at that address, thus allowing us to access that data via indirection. If that data happens to be another pointer, we have an extra layer of indirection between the pointer to pointer variable and the object being pointed at.

We cannot do this with references. References are easier to work with (provided we can be sure the reference will always be non-NULL) but, once assigned, we cannot reassign them like we can a pointer variable. That is, references must always refer to whatever object we initially assigned to them. But pointers are variables, thus we can reassign them any valid address, including NULL, at any time. So although pointers are slightly more complex than references and consume more memory than references, they are more flexible than references.

New programmers are often confused by the terms reference and pointer. This is understandable, particularly for C programmers moving to C++ because C has no concept of a reference (A C reference is the same as a C pointer). References are perhaps best understood using the following example:

class person {};

person Robert;

Here we've instantiated a person object named Robert. Whenever we refer to Robert we're actually referring to the memory address allocated to Robert. This memory address is not physically stored anywhere (as it would be if we assigned Robert to a pointer variable), we simply identify the address by the name Robert (or rather, &Robert).

person& Bob = Robert;

Here we've assigned Robert to the reference named Bob. Thus Bob and Robert both refer to the same memory address (Robert's address). In other words, Bob is an alternate name, an alias, for the memory allocated to Robert. We don't need the address-of operator to perform the assignment because we're assigning an object to a reference (&), not a pointer (*). The compiler knows the difference.

Note that Bob is neither a variable nor a constant. We haven't actually stored the memory address of Robert as we would were Bob a pointer variable. Since it is not a variable, we cannot reassign Bob to another person object and thus treat the two as being separate people (we can with pointers, but not with references). Indeed, if we did assign another person to Bob, we'd actually be invoking Robert's assignment operator (because Bob refers to Robert), thus Robert will end up copying the member data of that other person object and assigning that data to its own members. Robert then becomes a different person but a person who can still be referred to as either Bob or Robert. They are still one and the same person.

We can take this concept to extremes:

person& Bobby = Bob;

person& Rab = Robert;

person& Rabbie = Bobby;

person& Rob = Bob;

person& Robby = Rab;

Now we can refer to Robert as Rob, Bobby, Rab, Rabbie, Rob or Robby. Note how the reference we assign need not be the name we gave the original person object. They all refer to the same person object so any existing reference will do for assignment. And since references do not store memory addresses like pointers do, we can have as many different references to the same object as we like without consuming any additional memory in order to store the addresses, as we would with multiple pointers to the same object.

We would not normally use multiple references to the same object within the same code block, but passing references to different code blocks (functions) means those code blocks can refer to the same object by alternate names. This is important because the code block will not know the original name assigned to an object, but must refer to it in some way -- thus we use aliases.

void func (person& someone) {}

Thus if we pass Robert (or Bob, etc) into this function, the function will refer to Robert by the alias named someone. In turn, the function might pass someone into another function that perhaps uses the alias anyone. Thus that function refers to Robert by the alias anyone.

With pointers we do exactly the same thing except we pass a physical copy of the address of the person object:

void func2 (person* anyone) {}

Thus the anyone variable will store the address of Robert regardless of which alias (Bob, Rob, etc) we actually pass to the function, like so:

func2 (&Bobby);

Note that although Bobby is a reference (and therefore a memory address), we must use the address-of operator in order to pass by pointer. What we're actually doing is creating an automatic pointer variable whose value can be copied to the function's formal argument, anyone. If we don't use the address-of operator, the compiler will look for a signature that accepts Bobby by reference or by value, but will completely ignore any signature that accepts a pointer, because we didn't actually pass a pointer, we passed a reference.

How do you convert bases by using c plus plus?

The algorithm to convert from decimal to any other base is the same regardless of the base. Divide the decimal value by the base and take the remainder. This is the least significant digit. Repeatedly divide the result of the previous division by the base to get the next least significant digit, and so on until the result is zero.

Converting from any non-decimal base to any other base is slightly more difficult because C++ only recognises decimal and hexadecimal values (which are obviously converted to and from binary for our convenience). However since we must use character arrays to represent all other bases, the simplest solution is to convert those strings to decimal and then convert to the required base using the previously mentioned algorithm.

The following program provides 2 functions which allow relatively simple conversion from decimal to any base from 2 to 62, and back to decimal again. Note that Dec2Base() returns a null-terminated character array of the exact size required which can then be passed to Bin2Dec() to produce the original decimal value. Between these two functions you can convert from any base to any other base in the range 2 to 62. The test program output is shown at the bottom of the example.

#include <iostream>

// Convert to any base from 2 to 62 inclusive.

const char MAXBASE = 62;

// Note: Higher bases are possible, but we only have 61 symbols

// to play with (0-9, A-Z and a-z). Bases 11 through 36 are not

// case-sensitive (although we will use upper-case here), while

// higher bases use upper-case for the digits 10 through 35 and

// lower-case for the digits 36 through 61.

// Note that negative values use the '-' symbol, even in binary.

// Computers do not. Computers represent the value -1 as being

// 10000000 in 8-bit binary (the most significant bit represents

// the sign). The value -0 does not exist hence the least

// significant bit is zero, not 1 as might be expected. However,

// we humans can use the '-' symbol to differentiate positive

// and negative decimal values, so there's no reason not to

// follow this convention with all bases.

// Convert the given signed decimal value to the given base and

// return the buffer pointed to by the non-zero pointer to pointer.

char * Dec2Base( int dec, char base, char ** buffer )

{

// The pointer-to-pointer MUST be non-zero.

if( !buffer )

return( 0 );

// Point to the actual buffer (may be NULL).

char * p = *buffer;

// Check validity.

if( dec && base > 1 && base <= MAXBASE )

{

// Some variables.

unsigned int size = 1;

int rem = dec;

// Is the value signed?

if( rem < 0 )

{

// Increase the initial size to cater for sign.

++size;

// Convert the value to a positive value.

rem = dec *= -1;

}

// Release the buffer, if required.

if( p )

free( p );

// Calculate the required buffer size.

while( rem /= base )

++size;

// Allocate a null-terminated buffer and zero it.

p = ( char * ) malloc( ++size );

memset( p, 0, size-- );

// Update the output parameter.

if( *buffer != p )

*buffer = p;

// Point to the null terminator.

p += size;

// Start with the least-significant first.

while( dec )

{

// Step back to the correct character.

--p;

// Determine the digit value (remainder of division).

rem = dec % base;

// Determine the symbol.

if( rem < 10 )

*p = '0' + rem;

else if( rem < 36 )

*p = 'A' + rem - 10;

else

*p = 'a' + rem - 36;

// Prepare for next digit.

dec /= base;

}

// Signed value?

if( p != *buffer )

{

--p;

*p = '-';

}

}

// Return the buffer.

return( *buffer = p );

}

int Base2Dec( char * buffer, char base )

{

// Initialise the return value.

int decimal = 0;

// The buffer MUST BE null-terminated!

unsigned int size = strlen( buffer );

// Point to the null-terminator.

char * p = buffer;

p += size;

// The least-significant column is always the units,

// with position value 1.

unsigned int posval = 1;

// Repeat until we reach the most-significant digit.

while( p != buffer )

{

// Step back to the digit.

--p;

// Store the the digit's value

unsigned int val = *p;

// Is it a sign?

if( val == '-' )

// Adjust the result.

decimal *= -1;

// Not a sign, must be a digit.

else

{

// Convert the digit to a decimal value.

if( val > 'a' )

{

val -= 'a';

val += 36;

}

else if( val > 'A' )

{

val -= 'A';

val += 10;

}

else

val -= '0';

// Multiply by the position value.

val *= posval;

// Increment the result.

decimal += val;

// Calculate the next position value.

posval *= base;

}

}

// Success.

return( decimal );

}

// Test program.

int main()

{

// The test value:

int decimal = -54321;

// Initialise a pointer.

char * buffer = 0;

// Compute all bases from 2 through MAXBASE.

char base = 1;

while( ++base <= MAXBASE )

printf( "%d in decimal is %s in base %u\n",

decimal, Dec2Base( decimal, base, &buffer ), base );

// Convert from MAXBASE back to decimal:

printf( "%s in base %d is %d in decimal\n", buffer, MAXBASE, Base2Dec( buffer, MAXBASE ));

// Don't forget to release the buffer!

if( buffer )

free( buffer );

// Success!

return( 0 );

}

Output:

-54321 in decimal is -1101010000110001 in base 2

-54321 in decimal is -2202111220 in base 3

-54321 in decimal is -31100301 in base 4

-54321 in decimal is -3214241 in base 5

-54321 in decimal is -1055253 in base 6

-54321 in decimal is -314241 in base 7

-54321 in decimal is -152061 in base 8

-54321 in decimal is -82456 in base 9

-54321 in decimal is -54321 in base 10

-54321 in decimal is -378A3 in base 11

-54321 in decimal is -27529 in base 12

-54321 in decimal is -1B957 in base 13

-54321 in decimal is -15B21 in base 14

-54321 in decimal is -11166 in base 15

-54321 in decimal is -D431 in base 16

-54321 in decimal is -B0G6 in base 17

-54321 in decimal is -95BF in base 18

-54321 in decimal is -7H90 in base 19

-54321 in decimal is -6FG1 in base 20

-54321 in decimal is -5I3F in base 21

-54321 in decimal is -5253 in base 22

-54321 in decimal is -4AFI in base 23

-54321 in decimal is -3M79 in base 24

-54321 in decimal is -3BML in base 25

-54321 in decimal is -3297 in base 26

-54321 in decimal is -2KDO in base 27

-54321 in decimal is -2D81 in base 28

-54321 in decimal is -26H4 in base 29

-54321 in decimal is -20AL in base 30

-54321 in decimal is -1PG9 in base 31

-54321 in decimal is -1L1H in base 32

-54321 in decimal is -1GT3 in base 33

-54321 in decimal is -1CXN in base 34

-54321 in decimal is -19C1 in base 35

-54321 in decimal is -15WX in base 36

-54321 in decimal is -12P5 in base 37

-54321 in decimal is -bNJ in base 38

-54321 in decimal is -ZRX in base 39

-54321 in decimal is -Xc1 in base 40

-54321 in decimal is -WCb in base 41

-54321 in decimal is -UXF in base 42

-54321 in decimal is -TGC in base 43

-54321 in decimal is -S2P in base 44

-54321 in decimal is -Qb6 in base 45

-54321 in decimal is -PUf in base 46

-54321 in decimal is -ORa in base 47

-54321 in decimal is -NRX in base 48

-54321 in decimal is -MUT in base 49

-54321 in decimal is -LaL in base 50

-54321 in decimal is -Kj6 in base 51

-54321 in decimal is -K4X in base 52

-54321 in decimal is -JHn in base 53

-54321 in decimal is -IXp in base 54

-54321 in decimal is -Hqa in base 55

-54321 in decimal is -HI1 in base 56

-54321 in decimal is -Gf0 in base 57

-54321 in decimal is -G8X in base 58

-54321 in decimal is -FZf in base 59

-54321 in decimal is -F5L in base 60

-54321 in decimal is -EaV in base 61

-54321 in decimal is -E89 in base 62

-E89 in base 62 is -54321 in decimal

How do you represent a C plus plus non-pure virtual function in UML?

All virtual functions (including pure-virtual functions) are represented in italics. All non-virtual functions are represented normally. There is no differentiation between pure and non-pure virtual functions, however some people append "=0" to distinguish the pure-virtual functions.

How do you prove what a b and c equals if a plus b plus c equals 24 and a2 plus b2 equals c2?

Roughly speaking, to get a unique solution - or at least, a limited number of solutions - if you have 3 variables, you need 3 equations, not just 2. With the two equations, you can get a relationship between the three variables, but not a unique value for a, b, and c.

To get the general relationship, solve both equations for "c", replace one in the other, and solve the resulting equation for "a" to get the relationship between the variables "a" and "b". Then, for any valid combination of values for "a" and "b", use the simpler of the original equations (a + b + c = 24) to get the corresponding value for "c".

Where does one initialize a Reference member of a class?

References must be initialised from the initialisation list of all the class constructors. This is not unusual, because all instance member variables, particularly embedded members, whether references or not, should always be initialised from the initialisation list in order to ensure the most efficient construction. The initialisation list also allows you to invoke specific base class constructors (where required), rather than the default base class constructor that would be called implicitly.

Note that you cannot initialise a reference with a default value (not even NULL), thus you cannot declare any constructor that does not implicitly pass the required references. In particular, this means you must not declare a default constructor (the compiler-generated version is not generated so long as you declare at least one other constructor). You must also explicitly disable the compiler-generated assignment operator because references cannot be re-assigned once instantiated. You disable this method by declaring it private, but without providing an implementation.

The following stripped-down example shows how to initialise a class that contains two member references:

class foo1 { /*...*/ };

class foo2 { /*...*/ }; // definitions omitted for brevity

class bar {

private:

// member references:

foo1& m_foo1;

foo2& m_foo2;

public:

// ctor and copy ctor with initialisation lists:

bar(foo1& f1, foo2& f2):m_foo1(f1), m_foo2(f2) {}

bar(const bar& b): m_foo1(bar.m_foo1), m_foo2(bar.m_foo2) {}

private:

// assignment operator (disabled):

bar& operator= (const bar&);

};

Note that the assignment operator is declared but is not implemented. Do not include curly braces in the declaration otherwise the method is not disabled and the compiler will complain about the lack of a return value in the implementation.

Note also that definitions can also be split from declarations as required,by defining the initialisation list in the source file rather than the header, like so:

// file: bar.hpp

class bar {

private:

// member references:

foo1& m_foo1;

foo2& m_foo2;

public:

// ctor and copy ctor:

bar(foo1& f1, foo2& f2);

bar(const bar& b);

private:

// assignment operator disabled:

bar& operator= (const bar&);

};

// file: bar.cpp

#include "bar.hpp"

bar::bar(foo1& f1, foo2& f2):m_foo1(f1), m_foo2(f2) {}

bar::bar(const bar& b): m_foo1(bar.m_foo1), m_foo2(bar.m_foo2) {}

Write a program in c to display isosceles triangle dy digit?

#include<stdio.h>

#include<conio.h>

void main()

{

int a,b,c;

clrscr();

printf("\n Enter the 3 sides of Triangle: ");

scanf("%d %d %d",&a,&b,&c);

printf("\nYour entered side is a=%d b=%d c=%d",a,b,c);

if(a==b && b==c && a==c)

{

printf("\n EQUILATERAL TRIANGLE.");//All sides equal in case of Equilateral triangle

}

else if(a!=b&&b!=c)

printf("\n SCALENE TRIANGLE."); //All sides unequal

else

printf("\n ISOCELES TRIANGLE."); //At least 2 sides equal

getch();

}

Does mentioning the array name gives the base address in all the contexts?

Mentioning the array name in C or C++ gives the base address in all contexts except one.

Syntactically, the compiler treats the array name as a pointer to the first element. You can reference elements using array syntax, a[n], or using pointer syntax, *(a+n), and you can even mix the usages within an expression. When you pass an array name as a function argument, you are passing the "value of the pointer", which means that you are implicitly passing the array by reference, even though all parameters in functions are "call by value".

There is, however, one very important distinction. While an array name is referentially the same as a pointer, it is not a pointer in that it does not occupy program referential space in the process. This means that, while you can change the value of a pointer, and thus the address to which it points, you can not change the value of an array name. This distinction is what we call R-Value (array or pointer) as opposed to L-Value (pointer only), i.e. can the object appear on the left sign of an assignment operator.

How do you write a c plus plus program to sort a vector of strings using MSD radix sort?

The standard library sort algorithm automatically uses MSD radix to sort strings:

std::vector<std::string> vs = {"a", "b", "c" "d", "ab"};

std::sort(vs.begin(), vs.end());

After sorting, the order will be: {"a", "ab", "b", "c", "d"}