C++ notes

From raju

inherit map

Maps can be inherited. For example, to cache a bunch of "foo" objects, one can use

    class fooCache : public map<string, foo>
        // more functions to manipulate cache

tags | derive a c++ class from a map

checklist when factoring out a function

1. Add a semicolon, remove class name in the new function's declaration.

2. Add a return statement in the new function's definition if the function is supposed to return a value.

possible fixes to common g++ errors

# error: XXX does not name a type

If XXX is declared by auto keyword, add -std=c++11 to the compilation command.

Tested on g++ 4.7.1

function declarations

Information that is available only in function declarations but not in the function definitions

  1. Whether a function is static, virtual etc.,
  2. If there is a default value supplied to the argument(s).

strings related

To replace all occurrences of a character in a string

See minastaros solution in http://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string


Type of iterators

The vector class supports a random access iterator, the most general kind. The list container only supports bidirectional iterators.

Complexity of operations

  • Inserting a new key (and an associated value) into a map, or lookup of the data associated with a key in a map, can take up to O(log(n)) time, where n is the size of the current map. This is potentially a bit slower than some hash tables with a good hashing function, and is due to the fact that the map keys are stored in sorted order for use by iterators.
  • The vector has relatively costly insertions into the middle of the vector, but fast random access, whereas the list allows cheap insertions, but slow access (because the list has to be traversed to reach any item). Some algorithms, such as merge sort, even have different requirements when applied to lists instead of vectors. For instance, merge sort on vectors requires a scratch vector, whereas merge sort on lists does not.
  • The size function on a list may take O(n) time, so if you want to do something simple such as test for an empty list, use the empty function instead of checking for a size of zero. If you want to guarantee that the list is empty, you can always use the clear function.
  • Searching for an element in a list will require O(n) time because it lacks support for random access


  • Lists can also be sorted using the sort function, which is guaranteed to take time on the order of O(n*log(n)). Note that the sort algorithm provided by the STL works only for random access iterators, which are not provided by the list container, which necessitates the sort member function:
  • Lists can be reversed using

static variables

IDE reviews

Programming questions

Q. How to convert a string to const char *?

A. Use the c_str() function to get a const char * from std::string.

std::string str;
const char * c = str.c_str();

Ref:- http://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char

Q. vector of pairs vs map, which one to use?

A. http://stackoverflow.com/questions/454762/vector-or-map-which-one-to-use


  1. To remove an element - map::erase
  2. To find value by key - map::find
    map<string, int> myFruit;
    myFruit["apple"] = 1;
    myFruit["pear"] = 2;
    myFruit["grape"] = 3;
    string key;
    int value;
    auto it=myFruit.find(key);
    if (it != myFruit.end())
        cout << key << "'s number is " << it->second << "\n";
        cout << key << " is not found in the fruit map.\n";

What is the use of extern keyword

unit testing

  • cppunit can be used for unit testing in C++

They are in include/cppunit/TestAssert.h

  • To catch exceptions thrown by cppunit
    catch (CppUnit::Exception& x)
        clog << "Exception from CppUnit." << endl
             << x.what() << endl;
        return -1;

vector of strings

  • To iterate over vector of strings
    vector<string> a;
    for (vector<string>::const_iterator it = a.begin();
         it != a.end();
        const string& elem = *it;
        cout << elem << "\n";

In C++11

    for (auto i : a)
        cout << i << "\n";

Ref:- http://stackoverflow.com/questions/11170349/iterating-over-a-vector-of-strings-in-c

general tips

  • Let's say you have a member variable that can only be initialized by calling a function and it needs to be a constant private member (ex:- const map<string, int>). To initialize it
 Declare it as a reference to a constant static member variable (in .H file)
 Create a static member function that initializes this type of object and returns a reference to it (ex:- const map<string, int>&)
 Initialize the static private constant member variable to this function (in .C file)

So the header file looks as

    class a
        static const map<string, int>& _m;
        static const map<string, int>& _set_m();

and the source file looks as

    const map<string, int>& a::_m = a::_set_m();
    const map<string, int>&
        static map<string, int> m;
        m['apple'] = 1;
        m['banana'] = 2;
        m['cantaloupe'] = 3;
        return m;

External links