How to convert string to double dollars using C++ string stream, a STL container, and locale

How to convert string to double dollars using C++ string stream, STL containers, and locale

#include
#include
#include
#include
#include

using namespace std;

void to_dollar(int a);

int my_number_format(int num)
{
int idx;
char buffer[64];

idx = sizeof(buffer)-1;
buffer[idx–] = 0; // end zero

int count = 0;
while (num > 0) {
if (0 == idx)
return -1;
if (count > 2) {
buffer[idx–] = ‘,’;
if (0 == idx)
return -1;
count = 0;
}
count++;
buffer[idx–] = ‘0’+(num % 10);
num /= 10;
}

buffer[idx] = ‘$’; // currency sign
return printf(“%s\n”, &buffer[idx]);
}

int main()
{
int userInput;

cout << "Please enter an integer-:> ” << endl; cin >> userInput;
int result;
result=my_number_format(userInput);
return (0);
}

void to_dollar(int a)
{
stringstream inString;
string strTemp;
long double intTemp;

inString << a; // convert integer to string for easier handling inString.str(inString.str()+"00"); // concatenate two zeos to denote currency fractional digits inString >> intTemp; // convert back to integer

locale loc(“english_USA”); // set the locale
cout.imbue(loc);

cout.setf(cout.flags() | ios::showbase); // turn on currency sign printing
const money_put& m_put = use_facet >(loc); // get the money_put facet
m_put.put(cout, false, cout, ‘ ‘, intTemp); // show me the money. Note to use fractionally adjusted value.
cout << endl; }

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview question: How to merge one array into another also known as merge sort

C++ interview question: How to merge one array into another also known as merge sort

How to merge one array into another. A good example would involve a merge sort like:
void MergeSort(apvector &arrayA, apvector &arrayB, apvector &arrayC)
{
int indexA = 0; // initialize variables for the subscripts
int indexB = 0;
int indexC = 0;

while((indexA < arrayA.length( )) && (indexB < arrayB.length( )) { if (arrayA[indexA] < arrayB[indexB]) { arrayC[indexC] = arrayA[indexA]; indexA++; //increase the subscript } else { arrayC[indexC] = arrayB[indexB]; indexB++; //increase the subscript } indexC++; //move to the next position in the new array } // Move remaining elements to end of new array when one merging array is empty while (indexA < arrayA.length( )) { arrayC[indexC] = arrayA[indexA]; indexA++; indexC++; } while (indexB < arrayB.length( )) { arrayC[indexC] = arrayB[indexB]; indexB++; indexC++; } return; } The one powerful concept of arrays is their use to traverse the array as you can access each element using the same expression. All you need to is have an interated statement in which the variable i can be used as a counter incrementing from zero to the length minus one.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Covering C++ interviews questions on const, initialization list, global variables, and static

Covering C++ interviews questions on const, initialization list, global variables, and static
Note that non static const data members and reference data members cannot assign values. You would need to have these initialized in the initialization list.

Initialization lists can be listed as private after the constructor definition.
class Baz
{
public:
Baz() : _foo( “initialize foo first” ), _bar( “then bar” ) { }

private:
std::string _foo;
std::string _bar;
};

In order to access non static members of a class from a static method, you need to declare a class instance inside the static instance. A static method can only use in class’s role is to use static members only. Static methods can be accessed by non static and static data members. Static methods cannot be volatile, constant, or virtual. Also for example, for app.cpp or app.c:
static void print_some_data()
{
}
is limited in abc.cpp/c only, no other compilation unit in an application can use it.

A common use for static to keep track the number of instances of a class.
Static member functions are used to access private static data member and they do not have a this pointer. They can only access static data members as they are not attached to instances of objects.
To access static member of a class, use ::
In short:
1. Within a function, there is one copy of the variable that retains its value even when the function returns.
2. Within a class, all objects share the static variable and the static variable is accessed using the class name.
3. In the global scope a static variable is local to the current file.

2.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Detailed Explanation of C++ inline, this pointer, and name mangling

Detailed Explanation of C++ inline, this pointer, and name mangling
The inline function is used to tell the compiler to substitute the code within the function for every instance of a function call. This substitution happens at the discretion of the compiler. It will not take place if the code is too large to inline or if the address is taken.
A better explanation might be is to tell the compiler to insert the complete body of a function where ever it is called.
If you ever want to disable all optimization features, you could add the line asm(””);

This pointer is a pointer accessible only within member functions of a class or union type. It points to the object for which the member function is called. Note that static members do not have a static pointer.
If you ever decide to delete this pointer, the program will crash if it is done for an extern, static, or automatic object. There is now way it can tell if it was instantiated on the heap so the class cannot tell if it was properly instantiated. The calling program while deleting this pointer, it might not know how to exit from its demise. The class will think it is still in scope even though it was decided to zap itself. Dereferencing of this pointer can lead to disaster.
Name mangling involves process of encoding the parameters types with the functions or methods name into a unique name. The inverse is called demangling. An example would Foo::bar( int, long) would become bar_C#FooIL. Constructors are usually left out thus Foo::Foo(int, long) would become __C3Fooil

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ STL containers including differences of list vs vector

C++ STL containers including differences of list vs vector
Vector –
1> Insertion – O(n) /* Resizing the array */
2> Search – O(n) /* Sequential */ , O(logn ) /* Binary */
3> Random Access – Yes .
4> Deletion – O(n) /* Shifting & Resizing */
5> Sequential Memory used .

List –
1> Insertion – O(1)
2> Search – O(n)
3> Deletion – O(n)
4> Random Access – No
5> Linked allocation , hence more memory efficient
The above are known as containers found in the Standard Temple Library (STL) They also contain predefined behaviour and are well known interfaces.
Below is a C++ source example of a list:
// Standard Template Library example

#include
#include using namespace std;

// Simple example uses type int

int main()
{
list L;
L.push_back(0); // Insert a new element at the end
L.push_front(0); // Insert a new element at the beginning
L.insert(++L.begin(),2); // Insert “2” before position of first argument
// (Place before second argument)
L.push_back(5);
L.push_back(6);

list::iterator i;

cout << "before remove" <
#include

using namespace std;

main()
{
vector< vector > vI2Matrix; // Declare two dimensional array
vector A, B;
vector< vector >::iterator iter_ii;
vector::iterator iter_jj;

A.push_back(10);
A.push_back(20);
A.push_back(30);
B.push_back(100);
B.push_back(200);
B.push_back(300);

vI2Matrix.push_back(A);
vI2Matrix.push_back(B);

cout << endl << "Using Iterator:" << endl; for(iter_ii=vI2Matrix.begin(); iter_ii!=vI2Matrix.end(); iter_ii++) { for(iter_jj=(*iter_ii).begin(); iter_jj!=(*iter_ii).end(); iter_jj++) { cout << *iter_jj << endl; } } } Need finer detail of this with examples of map and multimap!!

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Handling Exceptions using try catch within C++ including why not to throw in a destructor

Handling Exceptions using try catch within C++ including why not to throw in a destructor
Here is an example typical try catch exception within C++ :

#include
#include

using namespace std;

class A {
~A() {
//throw new A; //this works but not suggested to throw in destructor
}
};

void foo()
{

throw new A;

}

int main()
{

try
{
foo();
}
catch (A * e)
{
cout<< "c works"; } catch (A & e) { cout<< "e works"; } return 0; } Compiler will always take care of the terminate() function call. Do not call throw from the destructor as it can cause stack corruption. It should only be logged. Remember destructors are called during the stack unwinding process. The run time system will then need to choose between handling the newly thrown exception (from destructor) or to handle the exception that already being processed. The run time system may also choose to terminate the application. You should always use an auto pointer for deleting exceptions. Exceptions are commonly called from constructors but this can be expensive. This can compile: #include
using namespace std;

// Example 1(a): Constructor function-try-block
//
class C {
C::C() {

try
{
int x=0;
}

catch( … )
{}
}
};

int main() {
return 0;
}

The best way to handle exceptions in constructors is to throw them since they have no return types.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

A C++ smart pointer including auto_ptr and shared_ptr and difference from Boost

C++ smart pointers including auto_ptr and shared_ptr

Note this is not complete!!

Smart pointers are used to prevent dangling pointers.
This is a demo of an auto_ptr:
#include
using namespace std;

class MyClass {
public:
MyClass() {} // nothing
~MyClass() {} // nothing
void myFunc() {} // nothing
};

int main() {
auto_ptr ptr1(new MyClass), ptr2;

ptr2 = ptr1;
ptr2->myFunc();

MyClass* ptr = ptr2.get();

ptr->myFunc();

return 0;
}
}
Auto_ptr has ownership but when you assign to another auto pointer, the assign auto pointer will lose ownership. The right hand side can also get modified.
Need to complete both types including shared_ptr within Boost. Need to know pros and cons of each.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

The complete guide to a C++ raw pointer

The complete guide to a C++ raw pointer
SomeClass *ptr=SomeClass();
SomeClass *ptr=SomeClass;

These two definitions are equivalent. Pointers can be slow and can be harder to debug pointer airthmatic code and data involving multiple pointers. Always set pointers to null after freeing otherwise your check for p != NULL will be useless which could cause memory corruption.
A dangling pointer arises when you the address of a pointer after its lifetime is over. This occurs when you are returning addresses of automatic variables from a function or using the address of a memory block that been freed.
The following code will not generate any errors unless indicated in the comments:

#include
using namespace std;

class base {
int i;
public:
void set_i(int x) { i = x; }
};
class derived: base {};

int main() {
//this does not generate error
/* int *p,*q;
p=&(*q);
cout<<"p"<FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

The complete guide to a C++ functor, callback function, and function pointer

The complete guide to a C++ functor, callback function, and function pointer
Note that functors are class operators that over the operator ().
Function pointer are are pointers to function. Virtual table is an example of this.
Callback functions are function pointers are function pointers passed as function parameters. This could be called if an event occurs. For example, if a thread is created we could use a callback function to be called.
An example of a callback function is:
// Callbacks in C++
// Refer to http://www.cscene.org for detailed docs.
//
// Copyright (c) 1998 by Juergen Hermann
//
// To make things easy, we put all code in one file.
// Large parts of this should go to thread.hpp/cpp in real real life.
// Compiled using VC++ 5.0 on Windows NT 4 as a console application.

#include
#include
#include

#include
#include

#define WIN32_LEAN_AND_MEAN
#include

///////////////////////////////////////////////////////////////////////
// Utility stuff
///////////////////////////////////////////////////////////////////////

inline int randrange(int lo, int hi)
{
return rand() / (RAND_MAX / (hi – lo + 1)) + lo;
}

///////////////////////////////////////////////////////////////////////
// A thread base class
///////////////////////////////////////////////////////////////////////

class Thread {
public:
virtual ~Thread() {}
void run();
unsigned long pid() const { return m_pid; }

protected:
Thread();
virtual void code() = 0;

private:
int running;
unsigned long m_pid;

static void dispatch(void* thread_obj);
};

Thread::Thread()
: running(0)
, m_pid(0L)
{
}

void Thread::run()
{
// Don’t start two threads on the same object
if (running) return;

// Create an OS thread, using the static callback
m_pid = _beginthread(Thread::dispatch, 0, this);
running = 1;
}

void Thread::dispatch(void* thread_obj)
{
// Call the actual OO thread code
((Thread*)thread_obj)->code();

// After code() returns, kill the thread object
delete (Thread*)thread_obj;
}

///////////////////////////////////////////////////////////////////////
// An example thread class
///////////////////////////////////////////////////////////////////////

class Dice : private Thread {
public:
static void Dice::create(const char* dicename);
static CRITICAL_SECTION sync;

private:
Dice(const char* dicename) : name(dicename) {}
virtual void code();

std::string name;
};

CRITICAL_SECTION Dice::sync;

void Dice::create(const char* dicename)
{
(new Dice(dicename))->run();
}

void Dice::code()
{
EnterCriticalSection(&sync); // Waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership Microsoft specific

std::cout << "Started thread #" << pid() << " for " << name.c_str() << std::endl; LeaveCriticalSection(&sync); // Releases ownership of the specified critical section object (Microsoft specific) srand(time(0) * pid()); for (;;) { int val = randrange(1, 6); EnterCriticalSection(&sync); std::cout << name.c_str() << " rolled " << val << std::endl; LeaveCriticalSection(&sync); Sleep(randrange(100, 500)); // wait up to 500 ms } } /////////////////////////////////////////////////////////////////////// // Let's test! /////////////////////////////////////////////////////////////////////// int main() { InitializeCriticalSection(&Dice::sync); Dice::create("dice1"); Dice::create("dice2"); Sleep(5 * 1000L); // roll dice for 5 seconds return 0; // cleanup? what's cleanup? }

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

What are namespaces, functors, and iterator classes in C++?

What are namespaces, functors, and iterator classes in C++?
Namespaces reduced name collisions where an application may have various libraries of the same name. The using declaration makes it possible for a namespace without using a scope operator.
There are five types of iterator classes which input iterators, output iterators, forward iterators, and bidirectional iterators. These are usually stored in stored in lists and queues according to some ordering relation as defined in a binary tree.
Functors are a function pointer which holds the address of some pointer.
#include
using namespace std;

class Matcher
{
int target;
public:
Matcher(int m) : target(m) {}
int operator()(int x) { return x == target;}
};

int main() {
Matcher Is5(5);
int n=6;

if (Is5(n)) { // same as if (n == 5) return 0;
cout << "n and Is5 are equal" << endl; } else { cout << "not equal"< NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!