Sunday, September 14, 2014

C++ Contd..

Templates Mutex BST Linked List Hash Function Design Patterns

C++ Copy Constructor, Assignment Operator

Copy Constructor

Song(Song const&);
It is needed if you want to initialize an object to take the value of another one:
Song a;
Song b = a;    // Calls copy constructor
Assignment Operator
void operator=(const Song&);
It is needed for assigning a value to an already existing instance:
Song a;
Song b;
b = a;        // Calls assignment operator
Note that the standard return value for an assignment operator is a reference:
Song& operator=(const Song&);

C++ Singleton

#include <iostream>

using namespace std;

class Singleton
        static Singleton& getInstance()     // See Note 1.
            static Singleton instance;      // See Note 2.
                                            // Guaranteed to be destroyed.
                                            // Instantiated on first use.
            return instance;

        void Print();

        Singleton() {};                     // Constructor? (the {} brackets) are needed here.
                                            // Dont forget to declare these two. You want to make sure they
                                            // are unaccessable otherwise you may accidently get copies of
                                            // your singleton appearing.
        Singleton(Singleton const&);        // Copy Constructor. Don't Implement
        void operator=(Singleton const&);   // Assignment Operator. Don't implement

void Singleton::Print()
    cout << "I am a singleton" << endl;

int main(int argc, char *argv[])
    Singleton &S1 = Singleton::getInstance();    // Create/Instantiate Singleton 

    return EXIT_SUCCESS;

Note 1. Why does everybody want to return a singleton as a pointer? Returning it as a reference seems much more logical! You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object. Note 2. Use the static in a function method. This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free. This also means I don't need to add the object as a member because I have a static function with a static object inside it? Exactly, the object lives from first call to program termination, so it cannot be a plain data member. Note: Use a Singleton if:

  • If you need to have one and only one object of a type in system
Do not use a Singleton if:
  • If you want to save memory
  • If you want to try something new
  • If you want to show off how much you know
  • Because everyone else is doing it (See cargo cult programmer in wikipedia)
  • In user interface widgets
  • It is supposed to be a cache
  • In strings
  • In Sessions
  • I can go all day long
How to create the best singleton:
  • The smaller, the better. I am a minimalist
  • Make sure it is thread safe
  • Make sure it is never null
  • Make sure it is created only once
  • Lazy or system initialization? Up to your requirements
  • Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
  • Provide a destructor or somehow figure out how to dispose resources
  • Use little memory
If you need one and only one object, you create one and only one.
If there is no logical way that two instances could ever be accommodated without irreversibly corrupting the application, you should consider making it a singleton.
And then there's the other aspect, global access: If you don't need global access to the instance, it shouldn't be a singleton.

Thursday, September 11, 2014

C++ Object Slicing

"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away. For example,
class A {
   int foo;

class B : public A {
   int bar;
So an object of type B has two data members, foo and bar Then if you were to write this:
B b;

A a = b;
Then the information in b about member bar is lost in a. Situations where problems would arise If You have a base class A and a derived class B, then You can do the following.
void wantAnA(A myA)
   // work with myA

B derived;
// work with the object "derived"
Now the method wantAnA needs a copy of derived. However, the object derived cannot be copied completely, as the class B could invent additional member variables which are not in its base class A. Therefore, to call wantAnA, the compiler will "slice off" all additional members of the derived class. The result might be an object you did not want to create, because it may be incomplete, it behaves like an A-object (all special behaviour of the class B is lost).

C++ Interface Example

#include <iostream>
#include <vector>

using namespace std;

// Animal attribute/property is common between Cow and Dog, hence this is the interface
// that contains pure virtual functions of the property that is common to Cow and Dog
// Since this is pure abstract class (since it has a pure virtual function), this class 
// cannot be instantiated.
class Animal
    virtual void Speak() const = 0;

// Note:
// You can have an implementation of a pure virtual function.
// A derived class can explicitly call the base class implementation (if access permissions are allow it) 
// by using a fully-scoped name (by calling Animal::Speak(), if Animal::Speak() is public or protected (i.e. not private).

// The use case can be when there's a more-or-less reasonable default behavior, but the class 
// designed wants that sort-of-default behavior to be invoked only explicitly. 
// It can also be the case what you want derived classes to always perform their own work but also be able to call a common set of functionality.

// The other use could be for the case when you want to create a pure abstract class, but it does not have a pure virtual function.
// In that case you can make the destructor a pure abstract method and create the implementation for the destructor.

// Note that even though it's permitted by the language, it's not something that I see commonly used 
// (and the fact that it can be done seems to surprise most C++ programmers, even experienced ones).

void Animal::Speak() const
    cout << "Make some noise" << endl; 

class Cow : public Animal
    void Speak() const;

void Cow::Speak() const
    cout << "Moo" << endl;

class Dog : public Animal
    void Speak() const;

void Dog::Speak() const
    cout << "Woof" << endl;

void Speak(const Animal& animal)    // 1. Since we are passing a const reference, this can only call a const member function.
{                                   //    So we will have to make Animal::Speak() const and in turn Cow::Speak() and Dog::Speak() const
    animal.Speak();                 // 2. Passing a non const reference will let you modify Animal
}                                   // 3. Passing by value will lead to object slicing

int main(int argc, char *argv[])
    Cow myCow;
    Dog myDog;

    vector<Animal*> animalVec;      // You can't instantiate abstract classes, thus a vector of abstract classes can't work.
                                    // You can however use a vector of pointers to abstract classes.
                                    // Also storing by value i.e. vector<Animal> animalVec; will lead to object slicing

    for(vector<Animal*>::iterator iter = animalVec.begin(); iter != animalVec.end(); ++iter)

    return EXIT_SUCCESS;
Press any key to continue . . .

Wednesday, September 10, 2014

C/C++ Array

One dimensional array
                int foo [5];    // Array contains integers
Initialize: foo [5] = {1, 2, 3, 4, 5}; foo [5] = {1, 2, 3,}; // 3rd and 4th element are assigned zero foo [5] = {}; // All elements are assigned zero foo [] = {1, 2, 3, 4, 5}; Function: void procedure (int arg[]); Pass by value: Pass by reference: procedure (foo); Pass by pointer:
Two dimensional array
                int foo [2][3];     // [row x col] Array contains integers
                                    // Total row*col elements
Initialize: foo [2][3] = {{1, 2, 3}, {4, 5, 6}}; foo [2][3] = {1, 2, 3, 4, 5, 6}; foo [][] = {{1, 2, 3}, {4, 5, 6}}; foo [][] = {1, 2, 3, 4, 5, 6}; foo [2][3] = {{1, 2, 3}}; // All rest elements are assigned zero foo [2][3] = {}; // All elements are assigned zero

C/C++ Storage Classes

auto Default storage class for all local variables. Can only be used within functions, i.e., local variables.
register Used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). It should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
static Instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.
extern Defines a global variable that is visible to ALL object modules. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.
mutable (C++) Applies only to C++ class objects. It allows a member of an object to override constness. That is, a mutable member can be modified by a const member function.

Monday, September 8, 2014

C++ #define Vs typedef

#define typedef
Is a preprocessor token: the compiler itself will never see it. Is a compiler token: the preprocessor does not care about it.
Obeys scoping rules just like variables. Stays valid until the end of the file (or until a matching undef).
Is a preprocessor directive used to define macros or general pattern substitutions. For eg. #define MAX 100, substitutes all occurrences of MAX with 100 Creates an "alias" to an existing data type. For e.g. typedef char chr;
            #define INTPTR int*
            INTPTR a, b;
After preprocessing, that line expands to
            int* a, b;
Only a will have the type int *; b will be declared a plain int (because the * is associated with the declarator, not the type specifier).
        typedef int *INTPTR;
        INTPTR a, b;
In this case, both a and b will have type int *.

Sunday, September 7, 2014

C++ Const keyword

You have to read pointer declarations right-to-left.

            const int x = 10;
x's value cannot be changed
            int const x = 10;
Same as above
            static int x = 10;
Same as above
            const int const x = 10; 
This is nonsense. Pointers have two different kinds of const qualifiers makes sense, one is for the pointer itself, the other for what the pointer points. But it doesn't make sense for int type to have two different kinds of const qualifiers. Just use one
            foo const* p;
p points to a constant foo. The foo object can't be changed. It means p points to an object of class foo, but p can't be used to change that foo object (naturally p could also be NULL). For example, if class foo has a const member function called inspect(), saying p->inspect() is OK. But if class foo has a non-const member function called mutate(), saying p->mutate() is an error
            const foo* p
Same as above
            foo* const p;
p is a const pointer to a foo. You can't change the pointer p, but you can change the foo object
            foo const* const p;
p is a const pointer to a const foo.You can't change the pointer p itself, neither can you change the foo object
            const foo* const p;
            foo const& r;
It means r aliases a foo object, but r can't be used to change that foo object. For example, if class foo has a const member function called inspect(), saying r.inspect() is OK. But if class foo has a non-const member function called mutate(), saying r.mutate() is an error
            const foo& r;
Same as above
            foo& const r;
This is nonsense. r is a const reference to a foo. But that is redundant, since references are always const. You can't reseat a reference. Never. With or without the const. In other words, "foo& const r" is functionally equivalent to "foo& x". Since you're gaining nothing by adding the const after the &, you shouldn't add it since it will confuse people — the const will make some people think that the foo is const, as if you had said "foo const& x".
            int GetValue() const;
This member function cannot change this pointer, i.e. the class members of this pointer. It can however change any other
            const foo GetValue();
            const int& GetValue();
Returns a const reference to the member variable if it's a getter method. This won't make copies and return.
            int* GetValue();
            const int* GetValue();
            const int GetValue() const;
            const int& GetValue() const;
            int* GetValue() const;
            const int* GetValue() const;

Note: const class objects can only call const member functions

Three ways you can initialize a const member variable.
1. Inside the class declaration
static const int x = 10;
2. Outside the class
class A
   static const int a;

const int A::a = 10;    //defining the static member outside the class
Note: static means there is a single copy of the variable for all instances of the object, constant or not. It creates just one copy of it for all the objects. It is a design choice that needs to be considered carefully.
3. In constructor initialization list
class A
  const int b;
  A(int c):b(c){}    //const member initialized in initialization list

Note: "mutable" keyword is used with member variables which we want to be able to change even on const class objects. Hence, mutable data members of const objects can be modified
class A
    int x;
    mutable int y;
        x = 0;
        y = 0;
    void func() const
        i++;  // Error, cannot modify 
        j++;  // Works, because y is mutable
    void func()
        i++;  // Error, cannot modify 
        j++;  // Works, because y is mutable

int main()
    const A constObj;
    constObj.func();    // Calls the const func method, since constObj is const object

    A obj;
    obj.func();         // Call the non const func method, since obj is non const object

C++ Reference Vs Pointer

Reference Pointer
A reference is a variable that refers to something else and can be used as an alias for that something else. A reference is the object. A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, i.e. the compiler will apply the * operator for you. A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at that address.
Const references can be bound to temporaries. This makes const& safer for use in argument lists and so forth. Pointers cannot (not without some indirection).
    const int &x = int(12);     // legal C++
    int *y = &int(12);          // illegal to dereference 
                                // a temporary.
A reference cannot be reassigned, and must be assigned at initialization. A reference can not be re-seated/reassigned after binding. A reference, always refers to the object with which it is initialized A pointer can be re-assigned any number of times.
    int x = 5;
    int y = 6;
    int *p;
    p = &x;     // p points to x
    p = &y;     // p now points to y
    *p = 10;    // p now is 10

    // Another special example

    string s1("Nancy");  
    string s2("Clancy");  
    string& rs = s1;    // rs refers to s1  
    string *ps = &s1;   // ps points to s1 
    rs = s2;    // rs still refers to s1,  
                // but s1's value is now "Clancy", 
                // as if s1 = s2  
    ps = &s2;   // ps now points to s2;  
                // s1 is unchanged   
References always refer to an object. Because a reference must refer to an object, C++ requires that references be initialized
    string& rs;         // error! References must  
                        // be initialized  
    string s("xyzzy");  
    string& rs = s;     // okay, rs refers to s  
    int &r = NULL;      //<--- compiling error 
Pointers can point to nowhere (NULL).
    string *ps;     // uninitialized pointer
                    // Its valid but risky  
    int *p = NULL;
The fact that there is no such thing as a null reference implies that it can be more efficient to use references than to use pointers. That's because there's no need to test the validity of a reference before using it
    void printDouble(const double& rd)  
        cout << rd; // no need to test rd; it  
Pointers, on the other hand, should generally be tested against null.
    void printDouble(const double *pd)  
        if (pd) // check for null pointer
            cout << *pd;  
You can't test if a reference is NULL.
    if(&ref == NULL)    // Not possible
You can test if a pointer is NULL.
    if(*ptr == NULL)    // Possible
References only offer one level of indirection. You can have pointers to pointers to pointers offering extra levels of indirection.
You can't take the address of a reference. You can take the address of a pointer.
There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it e.g. &obj + 5). You can perform arithmetics with pointers, like post increment, pre increment. Pointers can iterate over an array, you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to.
Regardless of how a reference is implemented, a reference has the same memory address as the item it references. A pointer is a variable that holds a memory address.
References cannot be stuffed into an array. Pointers can be stuffed into an array.
A reference can be used directly. A pointer needs to be dereferenced with * to access the memory location it points to.
A reference to a class/struct uses . to access its members. A pointer to a class/struct uses -> to access its members.
There is one other situation in which you should use a reference, and that's when you're implementing certain operators. The most common example is operator[]. This operator typically needs to return something than can be used as the target of an assignment.
    vector <int> v(10);  // create an int vector of size 10;
    v[5] = 10;          // the target of this assignment
                        // is the return value of operator[]
If operator[] returned a pointer, this last statement would have to be written this way:
    *v[5] = 10;
But this makes it look like v is a vector of pointers, which it's not. For this reason, you'll almost always want operator[] to return a reference.

As a general rule,
Use references in function parameters and return types to define useful and self-documenting interfaces.
Use pointers to implement algorithms and data structures.

Wednesday, August 27, 2014

C++ Abstract and Interface fundamentals

Virtual Function A function preceded by virtual keyword. Intention is that this function would be overloaded in some derived classes. All virtual functions need not be overridden in some derived classes. They can remain in base class as it is.
            virtual void VirtualFunction();
Pure Virtual Function A virtual function with no implementation which is set equal to zero.
            virtual void PureVirtualFunction() = 0;
This can have an implementation in base class. You cannot instantiate a class having a pure virtual function. If you create a pointer of base class pointing to the derived class, it would call the function of the derived class. So, how do you use it?
            DerivedClass myDerivedClass;
            BaseClass* myBaseClass;
            myBaseClass = &myDerivedClass;      // In one line BaseClass* myBaseClass = &myDerivedClass;
            myBaseClass->PureVirtualFunction(); // This would call implementation of the pure virtual
                                                // function in derived class
You have to BOTH override AND implement a Pure Virtual Function in the class that derived from the class that had the pure virtual function. If no class derived from it, then it's not required.
Abstract Function Synonym for Pure Virtual Function. A function that is pure virtual.
            void AbstractFunction() = 0;
Abstract Class Class that has at least one Pure Virtual Function
Interface Class Class that has all functions Pure Virtual. And it has no member variables. This is not a rule per se. Intention is that the interface class will not have any implementation of its own. All required concrete class that derive from it must implement/override the functions in the interface. Note that there is a great temptation to add concrete member functions and data to iterface classes. This must be resisted, in general it is a sign that the interface is not well factored. Data and concrete member functions tend to imply a particular implementation and as such can inherit from the interface but should not be in that interface. A general test is the "is a" vs "has a", as in a Square is a Rectangle, but a Square has a set of sides. In other words, "is a" would use Abstract class and "has a" would use Interface.

Note: The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined. Note that a destructor must be defined even if it is declared pure-virtual. Ref:

Base Class/Super Class/Parent Class
Derived Class/Inherited Class/Sub Class
Abstract Function/Pure Virtual Function

Sunday, August 24, 2014

Convert FLV to MP4 or MKV without any loss

1. Demux the FLV using FLV Extract or
   FLVExtractCL -v -a INPUT.flv

2. Remux the video.264 and audio.aac to MP4 or MKV
   MP4Box -add videoFile.h264 -add audioFile.aac OUTPUT.mp4
   mkvmerge -o OUTPUT.mkv videoFile.264 audioFile.aac
   ffmpeg -i INPUT.flv -vcodec copy -acodec copy OUTPUT.mp4

Remember you need to set the correct framerate when muxing h264 video.
You can load the mp4 from ffmpeg directly into mkvmerge but I had a few issues so I just demux and then mux into mkv 
and I don't have any problems

Use MP4Box to extract raw streams from mp4 files
MP4Box -raw 1 -raw 2 INPUT.mp4
MP4Box -raw 1:output=filename INPUT.mp4
MP4Box -raw * INPUT.mp4

for users who dont like to code or type, a simple GUI for lossless packaging of RAW audio data (or RAW video data) is yamb.
I even prefer that to fixing FLV's with FLV Fix tools.

For example, when you (losslessly) extract *.264 and *.aac with FLVExtract and you then try to package them as *.mp4 with yamb,
then use the "Avg Frame Rate" (and not the "True Frame Rate") displayed by FLVExtract. yamb sometimes ask you to enter "frame
rate", sometimes it doesn't.

If the MP4 is still out of sync (audio vs. video), then use as "frame rate" the "videoframerate" as seen by "FLV Fix" (Replay
Media Catcher 4) after you have fixed the FLV with "Fix Duration".

Tuesday, August 12, 2014

Function: Parameter as Reference or Pointer

void funcParameterAsReference(int& inputOrOutput)
    inputOutputVal = 5;

int myInt = 0;
void funcParameterAsPointer(int* inputOrOutput)
    *inputOutputVal = 5;

int myInt = 0;
My rule of thumb is:
Use pointers if you want to do arithmetic with them or if you ever have to pass a NULL-pointer. Use references otherwise. So for input parameter use const reference and for output parameter use plain reference.
As input parameter :
void func(const int& input);
As output parameter :
void func(int& Output);
Why should pass-by-reference be used instead of pass-by-pointer? The most obvious reason is that a reference cannot be null. In a function that takes a pointer, you have to check that the pointer is not null before you use it, at least with a debug assertion. During a proper code review you have to analyze more code to be sure that you don't accidentally pass a null pointer to a function that doesn't expect one. I've found that it takes much longer to review functions that take pointer arguments for this very reason; it's so much easier to get it wrong when using pointers.
One advantage of using pointer as a parameter is when you have to add a new parameter to an existing function (for whatever reason). This way you can pass NULL to it, if it doesn't use the parameter in the implementation (definition)
void myFunc1(int* inp);
void myFunc2(int* inp);

int main()
    int inp = 0;
    myFunc1(&inp); // You can't pass NULL to myFunc1 because it uses inp in the implementation. If NULL is passed, 
                   // it will crash. 
                   // e.g. 
                   // int* inp = NULL;
                   // myFunc1(inp);
                   // OR
                   // myFunc1(NULL);

    cout << "inp = " << inp << endl;
    myFunc2(NULL); // You can pass NULL to myFunc2 because it doesn't use inp in the implementation

    return 0;

void myFunc1(int* inp)
    *inp = 99;
    cout << "I am in myFunc1" << endl;

void myFunc2(int* inp)  
    cout << "I am in myFunc2" << endl;  

Monday, May 5, 2014

PATHEXT environment variable

PATHEXT environment variable contains file extensions. This means for these file extensions, user doesn't have to type in the file extension to run the exe in a command prompt.

Batch file with same filename as the first command in it

If batch file has the same filename as the first command in it, running it causes it to run in a infinite loop. E.g. the batch file is named "ipconfig.bat" and it has ipconfig /flushdns What happens is when it hits the first command i.e. ipconfig /flushdns then it simply reenters the batch file. For example onsider if you have a batch file called "find.bat" echo this is find.bat. how are things. find /i %1 %2 What happens here? find .bat calls itself on the second line, because windows searches in the current directory first - the location of your batch file; for any file that has an extension defined in "PATHEXT" environment variable; defaults are exe,com,pif,vbs,js, and bat. So the find.bat that is currently executed is run instead of the intended find.exe that is in the system folder. So to avoid this problem, use any of the two approaches below 1. Rename the batch file to something different than the commands inside it. 2. Give explicit path to the command's exe for the commands in the batch file. E.g C:\Windows\System32\ipconfig /flushdns

Saturday, February 22, 2014

Sign In option doesn't appear in in Firefox

Sign In option is available on the Navbar on the top right corner.

Recently this appears to have disappeared when opened in Firefox.
This is a new issue and seems to occur because of some javascript issue and a filter rule in Fanboy's Social Blocking List in Adblock Plus.
The Filter rule causing this is ||$third-party. You need to disable this filter.
In Firefox, goto Tools → Adblock Plus → Filter preferences
Under Filter subscriptions tab, select Fanboy's Social Blocking List.

On the right side there are the filters. If you do not see the filters on right, hover your mouse on the dotted line on the right till a Hand appears, then click on it.

Scroll down to ||$third-party and uncheck it.

Close Adblock Plus Filter preferences.
Now open blogspot webpage or refresh an existing blogspot webpage. The Navbar should be back with the Sign In option.

Friday, February 21, 2014

C++ std::map

Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order. map<Key, Value>
Properties of maps

  1. Like Set, Map (ordered or unordered) does not allow duplicate Key
  2. Ordered map is sorted by it's Key. It is sorted following a specific strict weak ordering criterion indicated by its internal comparison object std::map::key_comp. So a map of user defined class objects which have no meaning of comparison, will not be sorted.
  3. Unordered map is not sorted by Key
  4. map is generally slower than unordered_map to access individual elements by their key map[Key]. So if std::find is mostly what you will be doing, unordered_map is better choice.
  5. unordered_map is generally less efficient for range iteration through a subset of it's elements than ordered map. So if iteration is mostly what you will be doing, then ordered map is a better choice.
  6. Maps are typically implemented as binary search trees.
  7. A unique feature of map among associative containers is that they implement the direct access operator (operator[]), which allows for direct access of the mapped value.
Proof of key uniqueness and sorting properties
cout << "Ordered Map" << endl;
cout << "===============================" << endl;
map<int, string> myMap;
myMap.insert(make_pair(33, "Hello"));
myMap.insert(make_pair(11, "Cello"));
myMap.insert(make_pair(11, "Vello"));
myMap.insert(make_pair(44, "Jello"));
myMap.insert(make_pair(22, "Fello"));

for(map<int, string>;::iterator iter = myMap.begin(); iter != myMap.end(); ++iter)
    cout << "<Key, Value> = <" << iter->;first << ", " << iter->;second << ">" << endl;

cout << endl;
cout << "Unordered Map" << endl;
cout << "===============================" << endl;
unordered_map<int, string> myUnorderedMap;
myUnorderedMap.insert(make_pair(33, "Hello"));
myUnorderedMap.insert(make_pair(11, "Cello"));
myUnorderedMap.insert(make_pair(11, "Vello"));
myUnorderedMap.insert(make_pair(44, "Jello"));
myUnorderedMap.insert(make_pair(22, "Fello"));

for(unordered_map<int, string>::iterator iter = myUnorderedMap.begin(); iter != myUnorderedMap.end(); ++iter)
    cout << "<Key, Value> = <" << iter->first << ", " << iter->second << ">" << endl;
Ordered Map
<Key, Value> = <11, Cello>
<Key, Value> = <22, Fello>
<Key, Value> = <33, Hello>
<Key, Value> = <44, Jello>

Unordered Map
<Key, Value> = <33, Hello>
<Key, Value> = <11, Cello>
<Key, Value> = <44, Jello>
<Key, Value> = <22, Fello>
Find in a map by Key
if(myMap.find("f") != myMap.end()) 
    // Found
    // Not found
Find in a map by Value
There are four options
  1. Use boost::bimap if boost library is available
  2. Create another map with Value as the Key and use map::find on it
  3. Use std::find_if with a predicate/functor in which you define some equal to comparison logic
  4. Iterate through the whole map to find the value
    for(map<int, string>::iterator iter = myMap.begin(); iter != myMap.end(); ++iter)
        if(iter->second == "Hello")
            // Found
Option 1 & 2 are equivalent. Runtime will be O(log n) for a map and O(1) for an unordered map. Option 2 you are essentially reinventing the boost:bimap. Option 3 & 4 are equivalent. Runtime in both cases is O(n). They both iterate the whole map entry-by-entry until a matching entry is found. Hence, if boost library is not available, go for option 2. Create two maps and implement functionality to keep them synchronized.

Free memory from a map of object pointers
  • map or any STL container destroys it's elements while being destroyed itself. If the map had stored some objects, those objects will be destroyed. If it had stored pointers, those pointers will be destroyed, but not the actual objects pointed to by the pointers. So, you have to destroy those instances by yourself explicitly, iterate through std::map elements and call delete on contained pointer.
  • std::map::clear() empties out the contents of the map, i.e. all contained pointers will be destroyed. It doesn't do anything with the objects pointed by them, in particular it doesn't delete them. All those objects will stay alive in memory.
Note: Raw pointers do not have ownership of the objects they point to. So when a pointer is destroyed, it will not delete whatever it points to. Generally speaking, when you have a pointer, there is no way to know if:
  • It points to a valid object at all (you don't want to call delete on some random garbage in memory),
  • The object it points to has been allocated with new (if it has been allocated in another way, it should not be deleted with delete), or
  • If there are other pointers that also point to the same object (in which case only one of them should call delete. Which one?)
So even if you wanted to, there is no way to automatically delete an object when a pointer to it is destroyed.

Sunday, February 9, 2014

C++ Functor Predicate with std::find_if

struct StringFinder
  StringFinder(const std::string & st) : s(st) { }
  const std::string s;
  bool operator()(const RegPair& lhs) const { return lhs.first == s; }

std::find_if(sequence.begin(), sequence.end(), StringFinder(foo));

That's not how predicates work. You have to supply either a free function bool Comparator(const MyClass & m) { ... }, or build a function object, a class that overloads operator():

struct MyClassComp
  explicit MyClassComp(int i) n(i) { }
  inline bool operator()(const MyClass & m) const { return m.myInt == n; }
  int n;

std::find_if(v.begin(), v.end(), MyClassComp(5));

A Functor is a object which acts like a function. Basically, a class which defines operator().

class MyFunctor
     int operator()(int x) { return x * 2;}

MyFunctor doubler;
int x = doubler(5);

The real advantage is that a functor can hold state.

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

Matcher Is5(5);

if (Is5(n))    // same as if (n == 5)
{ ....}

a functor is an object that acts like a function, i.e. it overloads the function call operator.

Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy functor that multiplies it's argument by a specified amount:

class MultiplyBy {
    int factor;

    MultiplyBy(int x) : factor(x) {

    int operator () (int other) const {
        return factor * other;

Then you could pass a MultiplyBy object to an algorithm like std::transform:

int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}

Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.

You can do it with a functor or a regular function that is not part of MyClass, or with a static function inside MyClass - here's an example with non-member function (basically just removing the MyClass:: part of the condition definition):


using namespace std;

class Foo

class MyClass
  int myInt;
  vector foo_v;

bool condition(MyClass mc)
    return true;
    return false;

int main (void)
  vector myClass_v;

C++ Comparison Operator overloading

#include <string>
#include <vector>
class A
 std::vector <std::string> m_member;

 A(std::vector <std::string> input); 
 const std::string GetValue() const;
 bool operator==(const A& rhs) const;
#include <string>
#include <vector>
#include "A.hpp"

A::A(std::vector <std::string> input) : m_member(input)

const std::string A::GetValue() const
    std::string returnString;
    for(std::vector <std::string>::const_iterator iter = m_member.begin(); iter != m_member.end(); ++iter)
     returnString = returnString + *iter;
    return returnString;

bool A::operator==(const A& rhs) const
    std::string rhsValue = rhs.GetValue();
    std::string lhsValue = this->GetValue();
    //Equality is true if lhsValue is equal to rhsValue
    return (lhsValue == rhsValue);
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include "A.hpp"

using namespace std;

int main(int argc, char *argv[])
    vector <string> input1;
    vector <string> input2;
    vector <string> input3;
    vector <string> input4;
    A obj_A1(input1);
    A obj_A2(input2);
    A obj_A3(input3);
    A obj_A4(input4);
    vector <A> A_vec;
    A* obj_p_A1 = new A(input1);
    A* obj_p_A2 = new A(input2);
    A* obj_p_A3 = new A(input3);
    A* obj_p_A4 = new A(input4);
    cout << obj_p_A2->GetValue() << endl;
    cout << obj_p_A4->GetValue() << endl; 
    vector <A*> A_p_vec;
    if(obj_A2 == obj_A4)
        cout << "objects are equal" << endl;
        cout << "objects are NOT equal" << endl;

    if(find(A_vec.begin(), A_vec.end(), obj_A4) != A_vec.end())
        cout << "obj_A4 found in A_vec" << endl;
    if(*obj_p_A2 == *obj_p_A4)
        cout << "objects pointers are equal" << endl;
        cout << "objects pointers are NOT equal" << endl;

    //if(find(A_p_vec.begin(), A_p_vec.end(), obj_p_A4) != A_p_vec.end()) // Overloaded comparison operator not 
                                                                          // called because pointer obj_p_A4 
                                                                          // has been used.
    //    cout << "*obj_p_A4 found in A_p_vec" << endl;

    return EXIT_SUCCESS;

Tuesday, January 21, 2014

C++ Code snippets

  1. Pre increment and Post increment: Difference

    Pre increment: ++i
    int i, x;
    i = 2;
    x = ++i;
    // now x = 3, i = 3 (x got assigned the incremented valued of i)
    Post increment: i++
    int i, x;
    i = 2;
    x = i++; 
    // now x = 2, but i = 3 (x got assigned the value of i (i.e. 2) and then i was incremented)
  2. For loop: Sequence of events
    for(Initialization; Condition; Increase)
    1. Initialization is executed. Generally, this declares a counter variable, and sets it to some initial value. This is executed a single time, at the beginning of the loop.
    2. Condition is checked. If it is true, the loop continues; otherwise, the loop ends.
    3. Statement is executed.
    4. Increase is executed, and the loop gets back to step 2.
    Because (2) and (4) are decoupled, either pre or post-increment can be used.

    The three fields in a for-loop are optional. They can be left empty, but in all cases the semicolon signs between them are required.
    For example, for( ;n<10; ) is a loop without initialization or increase (equivalent to a while-loop); and for( ;n<10; ++n) is a loop with increase, but no initialization (maybe because the variable was already initialized before the loop). A loop with no condition is equivalent to a loop with true as condition (i.e., an infinite loop).

  3. Delete NULL pointer
    Is it safe to call delete on a NULL pointer? Or in other words, do I need to check for non null pointer before calling delete?
    Yes it is safe to call delete. You do not need to check for null pointer before deleting.

    From the C++0x draft Standard.
    $5.3.5/2 - "[...]In either alternative, the value of the operand of delete may be a null pointer value.[...'"

  4. String: Remove the first occurrence of a character in string
    std::string myString;
    auto pos = myString.find('d');
    if(pos != std::string::npos)
        myString.erase(pos, 1);

  5. String: Remove all occurrences of a character in string
    std::string myString;
    myString.erase(std::remove(myString.begin(), myString.end(), 'd'), myString.end());

  6. String: Get the last element in string
    std::string myString;
    char ch = *myString.rbegin();

  7. String: Find the last occurrence of a character in string
    std::string myString;
    unsigned found = myString.find_last_of(":");

  8. String: Extract the end string after the last occurrence of a string
    std::string myString;
    unsigned found = myString.find_last_of(":");

  9. String: Get the string between two delimiters in string
    std::string myString;
    unsigned first = myString.find(START_DELIMITER);
    unsigned last = myString.find(END_DELIMITER);
    std::string newString = myString.substr(first, last-first);

  10. String: Count the number of occurrences of a character
    std::string myString = "a_b_c";
    int count = std::count(myString.begin(), myString.end(), '_');

  11. Length of array
    int a[7];
    std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;  
    This doesn't work on pointers, though, i.e. it won't work for either of the following:  
    int *p = new int[7]; 
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
    void func(int *p) 
        std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl; 
    int a[7]; 
  12. Convert Array to Vector
    int array[] = {1, 2, 3};
    int size = sizeof array / sizeof *array;
    std::vector vec(array, array + size);
    int myArray[3]={1, 2, 3};
    std::vector myVec(myArray, myArray + sizeof myArray / sizeof myArray[0]);
  13. Convert Vector to Array
    std::vector myVec;
    if(myVec.size() > 0)
        double* myArray = &myVec[0];    //Would cause "vector subscript out of range" runtime error if vector size is not  
    }                                   //greater than zero, because it tries to access the first (zeroth) element of vector
  14. Vector: Get iterator from index
    vector::iterator nthIter = myVec.begin() + index;
  15. Vector: Get index from iterator
    std::vector myVec;
    int index = iter - myVec.begin();
  16. Vector: Remove an element
    The standard sequence-container erase-remove idiom:
    myVec.erase(std::remove(myVec.begin(), myVec.end(), value_to_remove), myVec.end());
    Erasing invalidates iterators and references at or after the point of the erase, including the end() iterator.
    Erase returns a new iterator that points to the element immediately after the element(s) that were erased (or to the end if there is no such element).
    For example the vector had elements {1, 2, 3, 3, 4, 5} and you want to remove 3. You start iterating and the moment it finds the first 3, erase will remove it from the vector, but it will return an iterator to the next element after the first 3 (i.e. the next 3). So during the nest iteration after erase, the iterator would have been bumped up twice and hence during the next iteration it will skip removing the next 3. Result will be {1, 2, 3, 4, 5}
    What happens during remove is that remove compacts the elements that differ from the value to be removed (value_to_remove)
    to the beginning of the vector and returns the iterator to the first element after that range. The elements substituted in place of value_to_remove at the end after compacting are unspecified. So, using remove the vector becomes {1, 2, 4, 5, ?, ?} and it return a pointer to the first "?". Then erase is used in the range from the first "?" to the end of the vector, so it removes all these elements (who's value is unspecified). So now the vector becomes {1, 2, 4, 5}
  17. Vector: Check if it contains duplicate elements
    First std::sort.
    Then  std::unique.
    std::sort(myVec.begin(), myVec.end());
    bool hasDuplicateElements = std::unique(myVec.begin(), myVec.end()) != myVec.end();
    //Getting a new container with no duplicates
    std::unique_copy(myVec.begin(), myVec.end(), std::back_inserter(newMyVec));
    //Remove duplicates from a vector
    std::sort(myVec.begin(), myVec.end());
    myVec.erase(std::unique(myVec.begin(), myVec.end()), myVec.end());
  18. Vector: set_symmetric_difference

    std::sort(firstVec.begin(), firstVec.end());
    std::sort(secondVec.begin(), secondVec.end());
    set_symmetric_difference(firstVec, firstVec, secondVec, secondVec, std::back_inserter(symmetricDifferenceVec));
  19. Vector: set_difference

    std::sort(firstVec.begin(), firstVec.end());
    std::sort(secondVec.begin(), secondVec.end());
    set_difference(firstVec, firstVec, secondVec, secondVec, std::back_inserter(symmetricDifferenceVec));
  20. Set: Check if an element being inserted is already present
    Elements in a set are unique. For a similar container allowing for duplicate elements use multiset.
    std::set mySet;
        cout << "Element is already present in Set and will not be inserted" << endl;
  21. Map: View a Map
    std::map<string,int> myMap;
    for(std::map<string,int>::iterator iter = myMap.begin(); iter != myMap.end(); ++iter)
        cout << "String = " << iter->first << endl;
        cout << "Integer = " << iter->second << endl;
  22. Map: Free up memory of a map of pointers
    std::map<int, A*> myMap;
    A* obj_A1 = new A;
    A* obj_A2 = new A;
    A* obj_A3 = new A;
    myMap.insert(std::make_pair(11, obj_A1));
    myMap.insert(std::make_pair(22, obj_A2));
    myMap.insert(std::make_pair(33, obj_A3));
    delete myMap[11];
    delete myMap[22];
    delete myMap[33];
    for(std::map<int, A*>::iterator iter = myMap.begin(); iter != myMap.end(); ++it)
        delete iter->second;
  23. Map: Obtain the previous value by iterating
    map<int, std::string> myMap;
    myMap.insert(make_pair(11, "Cello"));
    myMap.insert(make_pair(22, "Hello"));
    myMap.insert(make_pair(33, "Jello"));
    for(map<int, string>::iterator iter = myMap.begin(); iter != myMap.end(); ++iter)
        if(iter != myMap.begin())    //Need to check if iterator is not the first one, because there is nothing previous to it
            cout << "Previous Value = " << (--iter)->second << endl;    //Need to pre-decrement the iterator to get the previous value
            ++iter;    //Need to increment the iterator, since it was decremented above (post or pre increment doesn't matter here, since no operation is done on the iterator)
  24. Map: Remove an element
    The standard associative-container erase idiom:
    for(std::map::iterator iter = myMap.begin(); iter != myMap.end(); /* no iterator increment */)
  25. Map: Find and Replace an element
    std::map myMap;
    myMap.insert(std::make_pair('c', 0));  // c is for cookie
    std::map::iterator iter = myMap.find('c'); 
    if(iter != myMap.end())
        iter->second = 42;
  26. Map: Check if an element being inserted is already present
    Element keys in a map are unique. For a similar container allowing for duplicate elements, use multimap.
    std::map myMap;
    myMap.insert(std::make_pair(11, "Hello"));
    myMap.insert(std::make_pair(22, "Jello"));
    if(!(myMap.insert(std::make_pair(11, "Fello"))).second)
        cout << "Key is already present in Map and will not be inserted" << endl;
  27. Class: Initialization List
        A(int row, int col): m_row(row), m_col(col) {};
    Combination of header and implementation file
        A(int row, int col);
    A::A(int row, int col) : m_row(row), m_col(col) 
  28. Class: Best Get and Set methods
    const std::vector& MyClass::GetMyVector() const
        return  m_myVector;
    void MyClass::SetMyVector(const std::vector& vector)
        m_myVector = vector;
  29. Class: Singleton Design Pattern
    class MySingletonClass
            static MySingletonClass& getInstance()
                static MySingletonClass    instance;      // Guaranteed to be destroyed.
                                                          // Instantiated on first use.
                return instance;
            MySingletonClass() {};                        // Constructor? (the {} brackets) are needed here.
                                                          // Don't forget to declare these two. You want to make sure they
                                                          // are inaccessible otherwise you may accidently get copies of
                                                          // your singleton appearing.
            MySingletonClass(MySingletonClass const&);    // Copy Constructor. Don't Implement
            void operator=(MySingletonClass const&);      // Assignment (=) Operator. Don't implement
  30. Class: When do you need to make your destructor virtual
    • if someone will derive from your class,
    • and if someone will say new Derived, where Derived is derived from your class,
    • and if someone will say delete p, where the actual object's type is Derived but the pointer p's type is your class.
    • or
    • No intention to derive classes from it
    • No instantiation on the heap
    • No intention to store in a pointer of a superclass
  31. Class: Overloading Comparison Operator
    std::find require the value to be equality comparable, and the compiler does not automatically define/generate you a default operator==. So if you don't write one yourself, objects of your class can't be compared for equality.
    std::find is a function template and it uses argument-dependent lookup (ADL) to find the right operator== to use.
    So comparison operator== needs to be overloaded with some comparison logic.
    Overloaded operator should be a public method.
    Built-in data types which includes pointers, don't use overloaded operator==
    So, even if comparison operator is overloaded, if pointers are used in std::find, the operator definition method won't be called.

    std::find doesn't take compare function.
    std::find_if doesn't take value.
    Alternatively, you can use std::find_if and supply a functor predicate.
    The compare function takes only one argument.

    std::find(strings.begin(), strings.end(), "hello");
    std::find_if(strings.begin(), strings.end(), compare);
    std::find_if(strings.begin(), strings.end(), compare("hello"));