Erasing from a vector by index

Use the vector::erase function to erase an element, or range of elements from a vector. It returns an iterator pointing to the element after the last one erased:

v.erase(v.begin() + pos);
v.erase(v.begin() + start, v.begin() + end);

For example, this program populates a vector with the numbers 0 to 9 and then erases 8, before erasing 3 to 5:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    typedef std::vector<int> intvec;
    intvec v(10);
    std::iota(v.begin(), v.end(), 0);
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    std::cout << "erase 8:\n";
    intvec::const_iterator it = v.erase(v.begin() + 8);
    std::cout << "next element is " << *it << "\n";
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    std::cout << "erase 3 to 5:\n";
    it = v.erase(v.begin() + 3, v.begin() + 6);
    std::cout << "next element is " << *it << "\n";
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
}

You can make a generic function to erase from a container by index by using std::advance to move to the first (and optionally last) element to remove and then calling the container’s own erase method:

template <class Container>
typename Container::iterator erase(Container& cont, size_t pos, size_t len = 1)
{
    typename Container::iterator it1 = cont.begin();
    std::advance(it1, pos);
    typename Container::iterator it2 = it1;
    std::advance(it2, len);
    return cont.erase(it1, it2);
}

Use it like this:

erase(vec, 8);    // erase 8
erase(vec, 3, 3); // erase 3 to 5

Note that this will be O(n) for lists because their iterators are not RandomAccessIterators.

Related

Lifetime of local static variables

Local static variables are constructed when the program flow first encounters their constructor call. This means that if control does not reach it, they will not be constructed.
They are destroyed at the end of the program. As with all objects, local statics are destroyed in reverse order of their creation.

#include <iostream>
#include <string>

struct Announcer {
    Announcer(const std::string& str) 
        : msg(str)
    {
        std::cout << "Created " << msg << "\n";
    }
    ~Announcer() 
    { 
        std::cout << "Destroyed " << msg << "\n";
    }
    std::string msg;
};

void func(bool condition) 
{
    if (condition) {
        static Announcer a1("in condition");
    }
    static Announcer a2("in func");
}

int main(int argc, char *argv[])
{
    func(argc > 1);
}

Running this without an argument produces:

Created in func
Destroyed in func

Because the code never enters the conditional in func(), a1 is never created.
Running it with an argument produces:

Created in condition
Created in func
Destroyed in func
Destroyed in condition

Here, the conditional has been entered, so a1 is created. Note the order of the destructor calls – in revese order to the order of construction.

Trim a string in C

Left trim

To left trim a string, find the length of prefix containing the characters to trim with strspn(), and then move the rest of the string forwards on top of it with memmove(), not forgetting to move the terminating nul character. Note that checking for the prefix being greater than zero will cover the case where the string is empty.

char *ltrim(char *str, const char *seps)
{
    size_t totrim;
    if (seps == NULL) {
        seps = "\t\n\v\f\r ";
    }
    totrim = strspn(str, seps);
    if (totrim > 0) {
        size_t len = strlen(str);
        if (totrim == len) {
            str[0] = '\0';
        }
        else {
            memmove(str, str + totrim, len + 1 - totrim);
        }
    }
    return str;
}

Right trim

To right trim, scan the string from the right and replace any characters to trim with nul characters, until you find a character you want to keep or you run out of string.

char *rtrim(char *str, const char *seps)
{
    int i;
    if (seps == NULL) {
        seps = "\t\n\v\f\r ";
    }
    i = strlen(str) - 1;
    while (i >= 0 && strchr(seps, str[i]) != NULL) {
        str[i] = '\0';
        i--;
    }
    return str;
}

Trim

To trim both ends of a string, just right trim it and then left trim it, or vice-versa.

char *trim(char *str, const char *seps)
{
    return ltrim(rtrim(str, seps), seps);
}

Test program

This tries all of the important cases with a space as the separator.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <trim.h>

size_t maxlen(char **strings, size_t len)
{
    unsigned int i;
    size_t max = 0;
    for (i = 0; i < len; i++) {
        if (strlen(strings[i]) > max) {
            max = strlen(strings[i]);
        }
    }
    return max;
}

int main(void)
{
    char *strings[] = {"", " ", "  " "test", " test", "test ", " test ",
        "  test", "test  ", "  test  "};
    const size_t n = sizeof(strings) / sizeof(char *);
    unsigned int i;
    char *str = malloc(maxlen(strings, n) + 1);
    for (i = 0; i < n; i++) {
        strcpy(str, strings[i]);
        trim(str, NULL);
        printf("%s\n", str);
    }
    free(str);
    return 0;
}

How to create, launch, and join a thread in C++

Contents

  • Method 1: Boost.Thread
  • Method 2: pthreads (POSIX)
  • Method 3: Windows threads
  • Method 4: std::thread (C++11)

Method 1: Boost.Thread

#include <iostream>
#include <string>
#include <boost/thread.hpp>

class Hello
{
public:
	void operator()(const std::string& msg) const
	{
		std::cout << msg << "\n";
	}
};

int main()
{
	boost::thread t = boost::thread(Hello(), "Hello");
	t.join();
}

Method 2: pthreads (POSIX)

#include <iostream>

#include <pthread.h>

void* hello(void *msg)
{
    std::cout << static_cast<const char*>(msg) << "\n";
    return NULL;
}

int main()
{
    pthread_t thread;
    pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    char msg[] = "Hello";
	int status = pthread_create(&thread, &attr, hello, msg);
	pthread_attr_destroy(&attr);
	if (status != 0) {
        std::cerr << "Failed to create thread\n";
        return 1;
	}
    status = pthread_join(thread, NULL);
    if (status != 0) {
        std::cerr << "Failed to join thread\n";
        return 1;
    }
}

Method 3: Windows threads

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <Windows.h>
#include <process.h>

#include <iostream>

void hello(void *msg)
{
	std::cout << static_cast<const char*>(msg) << "\n";
}

int main()
{
	char msg[] = "Hello";
	HANDLE thread = reinterpret_cast<HANDLE>(_beginthread(hello, 0, msg));
	if (thread == INVALID_HANDLE_VALUE) {
		std::cerr << "Failed to create thread\n";
		return 1;
	}
	WaitForSingleObject(thread, INFINITE);
}

Method 4: std::thread (C++11)

#include <string>
#include <iostream>
#include <thread>

void hello(const std::string& msg)
{
    std::cout << msg << "\n";
}

int main()
{
    std::thread t(hello, "Hello");
    t.join();
}

Setting up Facebook Folly on Ubuntu

This is how I installed the Facebook Folly C++ libraries on Ubuntu.

Step 1: The source

I downloaded master.zip from https://github.com/facebook/folly/archive/master.zip and unzipped it, creating the directory /home/martin/folly-master.

Step 2: Install prerequisites

I just installed everything mentioned in the README.md. I had most of these already:

sudo apt-get install \
    g++ \
    automake \
    autoconf \
    autoconf-archive \
    libtool \
    libboost-all-dev \
    libevent-dev \
    libdouble-conversion-dev \
    libgoogle-glog-dev \
    libgflags-dev \
    liblz4-dev \
    liblzma-dev \
    libsnappy-dev \
    make \
    zlib1g-dev \
    binutils-dev \
    libjemalloc-dev \
    libssl-dev
    libunwind8-dev \
    libelf-dev \
    libdwarf-dev
    libiberty-dev

Step 3: Build

autoreconf -ivf
./configure
make
sudo make install

I couldn’t get make check to work because Google Test has changed, so I skipped that step.

Step 4: Install header files

sudo mkdir /usr/include/folly
sudo mkdir /usr/include/folly/detail
sudo cp /home/martin/folly-master/folly/*.h /usr/include/folly
sudo cp /home/martin/folly-master/folly/detail/*.h /usr/include/folly/detail
sudo cp -r /home/martin/folly-master/folly/compatibility /usr/include/folly

I’m not sure if copying the header files from detail was necessary, but it doesn’t do any harm.

Step 5: Install the libraries

sudo cp /home/martin/folly-master/folly/.libs/libfolly.so.57.0.0 /usr/local/lib
cd /usr/local/lib
sudo ln -s libfolly.so.57.0.0 libfolly.so
sudo ln -s libfolly.so.57.0.0 libfolly.so.57
sudo ldconfig -v

Step 6: Try it

I wrote this program in hello.cpp:

#include <iostream>
#include <folly/FBString.h>

int main()
{
    folly::fbstring str("Hello, Folly World!");
    std::cout << str << "\n";
}

I compiled it like this:

g++ hello.cpp -o hello -lfolly

Finally, I ran it:

./hello
Hello, Folly World!

Success!

How to do string formatting in C++

Contents

  1. Use vsnprintf() (C++11 and POSIX)
  2. Use Boost.Format
  3. Use folly::format()

Method 1: Use vsnprintf() (C++11 and POSIX)

#include <iostream>
#include <vector>
#include <string>
#include <cstdarg>
#include <cstring>

std::string format(const std::string& format, ...)
{
    va_list args;
    va_start (args, format);
    size_t len = std::vsnprintf(NULL, 0, format.c_str(), args);
    va_end (args);
    std::vector<char> vec(len + 1);
    va_start (args, format);
    std::vsnprintf(&vec[0], len + 1, format.c_str(), args);
    va_end (args);
    return &vec[0];
}

int main()
{
    char str[] = "%s => %d";
    std::cout << string_format(str, "apples", 7) << "\n";
}

Method 2: Use Boost.Format

#include <iostream>
#include <boost/format.hpp>

int main()
{
    char str[] = "%s => %d";
    std::cout <<  boost::str(boost::format(str) % "apples" % 7) << "\n";
}

Reference: Boost Format library

Method 3: Use folly::format()

#include <iostream>
#include <folly/Format.h>

int main()
{
    char str[] = "{} => {}";
    std::cout <<  folly::format(str, "apples", 7) << "\n";
}

Reference: folly/Format.h

Related

Calling a base class virtual function from a derived class

You can call a base class version of a virtual function from a derived class by prefixing its name with the name of the base class. For example, if you have the following base class:

class Base
{
    public:
        virtual void method()
        {
            std::cout << "Base::method()" << "\n";
        }
        virtual ~Base()
        {
        }
};

You can call its version of method() within a derived class like this:

class Derived : public Base
{
    virtual void method()
    {
        Base::method();
        std::cout << "Derived::method()" << "\n";
    }
    virtual ~Derived()
    {
    }
};

Example program:

int main()
{
    Base *d = new Derived();
    d->method();
    delete d;
}
Base::method()
Derived::method()

Note that if the base class has inherited its version of a method, rather than implementing it, you will get the inherited version. So for example in the classes below, Parent inherits method() from Grandparent, and does not override it. If Child call’s Parent‘s version of method, the inherited one from Grandparent is called:

class Grandparent
{
    public:
        virtual void method()
        {
            std::cout << "Grandparent::method()" << "\n";
        }
        virtual ~Grandparent()
        {
        }
};

class Parent : public Grandparent
{
    public:
        virtual ~Parent()
        {
        }
};

class Child : public Parent
{
    virtual void method()
    {
        Parent::method();
        std::cout << "Child::method()" << "\n";
    }
    virtual ~Child()
    {
    }
};

Example program:

int main()
{
    Parent *p = new Child();
    p->method();
    delete p;
}
Grandparent::method()
Child::method()

See also: Calling the Base Class Constructor for how to call the base class constructor from a derived class, and Virtual Base Classes for how to call a base class method to disambiguate multiple inheritance.
See Typedef super for a handy idiom for referring to the base class.

is and == in Python

The is keyword tests whether two variables point to the same object. In other words this code:

a is b

Tests whether:

a.id() == b.id()

The == operator tests whether two objects have the same value. The meaning of this depends upon the type of the object.
It is defined in the obvious way for built-in types.

You can make your own types comparable with == by implementing __eq__():

class C(object):
    def __init__(self, val):
        self.val = val

    def __eq__(self, other):
        return self.val == other.val

c = C('spam')
d = C('spam')
print c == d
True

Note that because Python will cache and reuse object instances, two different objects that compare equal with == may also compare equal with is, but this should not be relied upon.

Mixins in Python

A mixin is a class which is used as an additional base class and adds the implementation of a feature, mixing it into the derived class. This allows derived classes to be assembled from components, adding only those features they require.

A good example of mixins is Werkzeug’s Request/Response Wrapper Mixins.

A typical Werkzeug application starts by taking the WSGI environment and constructs a Request object out of it:

def application(environ, start_response):
    request = Request(environ)

The Request class is often a user-defined class derived from werkzeug.wrappers.BaseRequest. This is a bare-bones class that does not provide features like E-Tags and cache control. In order for implementors to be able to add those features to their class, Werkzeug provides a number of mixins for HTTP features:

  • AcceptMixin for accept header parsing
  • ETagRequestMixin for etag and cache control handling
  • UserAgentMixin for user agent introspection
  • AuthorizationMixin for http auth handling
  • CommonRequestDescriptorsMixin for common headers

Implementors add one or more of these classes to the derivation list of their class to mix in the features they want:

from werkzeug.wrappers import AcceptMixin, BaseRequest

class Request(BaseRequest, AcceptMixin):
    pass

The implementor can then access attributes of the AcceptMixin from the Request class

mimetypes = request.accept_mimetypes

If this wasn’t done using mixins, it would be necessary to explicitly aggregate an object to implement the Accept headers when the Request object was constructed, something like this:

class Request(BaseRequest):
    def __init__(self):
        self.acceptor = AcceptComponent() # Not a real class

And then it would need to be accessed indirectly, something like this:

mimetypes = request.acceptor.accept_mimetypes # Not real code

So you can see that a mixin has simplified the construction and use of the class.

Two properties of mixins are:

  • By their very nature mixins are useless on their own – their sole purpose is to be mixed into other classes
  • They are tightly coupled to the classes into which they can be mixed in, since they must have intimate knowledge of them in order to be able to do anything useful

Deleting files and folders in Python

Deleting files

Use os.remove()

import os
os.remove(filename)

Deleting folders

Use os.rmdir()

import os
os.rmdir(dirname)

You will get an OSError if the directory is not empty.

Deleting whole trees

You can delete a non-empty directory and all of its descendants with shutil.rmtree()

shutil.rmtree(dirname)