Tag Archives: C++11

How to sleep for milliseconds in C++

  1. Use usleep (POSIX)
  2. Use Sleep (Windows)
  3. Use Boost.Thread
  4. Use std::this_thread::sleep_for (C++11)

Method 1: Use usleep (POSIX)

#include <unistd.h>

int main()
{
    usleep(500);
}

Method 2: Use Sleep (Windows)

#include <Windows.h>

int main()
{
    Sleep(500);
}

Method 3: Use Boost.Thread

#include <boost/thread/thread.hpp>
int main()
{
    boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}

Method 4: Use std::this_thread::sleep_for (C++11)

#include <chrono>
#include <thread>

int main()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
}

Promises and futures

The words "promise" and "future" have historically been used rather interchangeably in concurrent programming, but they have very particular meanings in C++.

A promise is an asynchronous provider – it provides a result to a shared state
A future is an asynchronous return object – it reads a result from a shared state, waiting for it if necessary

  1. You construct a promise of type T, and you are creating a shared state that can store a variable of type T
  2. You can get a future from this promise with get_future()
  3. You can set the value of the promise’s variable with set_value()
  4. The future can read the value of the variable when it becomes available with its get() method

Below is a simple example of creating a promise, getting a future from it, sending the future to a thread, setting the value of the promise, and finally retrieving it from the future.

#include <iostream>
#include <functional>
#include <thread>
#include <future>

template <typename T>
void print (std::future<T>& fut) {
    T x = fut.get();
    std::cout << "value: " << x << "\n";
}

int main()
{
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread thr (print<int>, std::ref(fut));
    prom.set_value(10);
    thr.join();
}

Populate a map with literal values

Method 1: Use parallel arrays

#include <map>
#include <string>

int main()
{
    typedef std::map<std::string, unsigned int> map_string_to_uint;
    const size_t n = 12;

    map_string_to_uint monthdays1;
    const char *months1[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
        "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
    unsigned int days1[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    for (int m = 0; m < n; ++m) {
        monthdays1[months1[m]] = days1[m];
    }
}

Method 2: Use an array of structs

#include <map>
#include <string>

int main()
{
    typedef std::map<std::string, unsigned int> map_string_to_uint;
    const size_t n = 12;

    map_string_to_uint monthdays2;
    struct Monthdays {
        const char *month;
        unsigned int days;
    };
    Monthdays months2[] =  {{"JAN", 31}, {"FEB", 28}, {"MAR", 31},
        {"APR", 30}, {"MAY", 31}, {"JUN", 30}, {"JUL", 31}, {"AUG", 31}, {"SEP", 30},
        {"OCT", 31}, {"NOV", 30}, {"DEC", 31}};
    for (int m = 0; m < n; ++m) {
        monthdays2[months2[m].month] = months2[m].days;
    }
}

Method 3: Use an array of std::pairs and the range constructor

#include <map>
#include <string>

int main()
{
    typedef std::map<std::string, unsigned int> map_string_to_uint;
    const size_t n = 12;

    std::pair<std::string, unsigned int> months3[] = {
        std::make_pair("JAN", 31), std::make_pair("FEB", 28), std::make_pair("MAR", 31),
        std::make_pair("APR", 30), std::make_pair("MAY", 31), std::make_pair("JUN", 30),
        std::make_pair("JUL", 31), std::make_pair("AUG", 31), std::make_pair("SEP", 30), 
        std::make_pair("OCT", 31), std::make_pair("NOV", 30), std::make_pair("DEC", 31)};
    map_string_to_uint monthdays3(months3, months3 + n);
}

Method 4: Use Boost.Assign

#include <map>
#include <string>
#include <boost/assign.hpp>

int main()
{
    typedef std::map<std::string, unsigned int> map_string_to_uint;

    map_string_to_uint monthdays4 = boost::assign::map_list_of ("JAN", 31) ("FEB", 28) ("MAR", 31)
        ("APR", 30) ("MAY", 31) ("JUN", 30) ("JUL", 31) ("AUG", 31) ("SEP", 30) 
        ("OCT", 31) ("NOV", 30) ("DEC", 31);
}

Method 5: Use a C++11 initializer

#include <map>
#include <string>

int main()
{
    typedef std::map<std::string, unsigned int> map_string_to_uint;

    /* Method 5: Use a C++11 initializer */
    map_string_to_uint monthdays5 =  {{"JAN", 31}, {"FEB", 28}, {"MAR", 31},
        {"APR", 30}, {"MAY", 31}, {"JUN", 30}, {"JUL", 31}, {"AUG", 31}, {"SEP", 30},
        {"OCT", 31}, {"NOV", 30}, {"DEC", 31}};
}

std::vector::emplace_back()

The emplace_back() method is a C++11 addition to vector that makes it more efficient to add an object to the back of a vector.

Consider the following code:

#include <iostream>
#include <vector>
#include <string>

class X
{
public:
    X(std::string s, int i)
        : s_(s), i_(i)
    {
        std::cout << "Constructor called for " << s_ << i_ << "\n";
    }
    X(const X& other)
        : s_(other.s_), i_(other.i_)
    {
        std::cout << "Copy constructor called for " << s_ << i_ << "\n";
    }
private:
    std::string s_;
    int i_;
};

int main()
{
    std::vector<X> v;
    std::cout << "push_back:" << "\n";
    v.push_back(X("A", 1));
}

An object of a class with 2 member variables initialised in the constructor is first constructed, and added to the end of a vector with push_back().

This is a 2-step process:

  1. Construct the object
  2. Copy it into the vector’s storage

The output from the program shows this process:

push_back:
Constructor called for A1
Copy constructor called for A1

Constructing an object, copying it, and then destroying it when it goes out of scope is not very efficient, and it’s this inefficiency that emplace_back is designed to remove.

emplace_back takes a variable list of arguments, which must match those of one of the object’s constructors, and these are forwarded to that constructor so that the object is constructed in-place.

    std::cout << "emplace_back:" << "\n";
    v.emplace_back("A", 1);

This produces the following output:

emplace_back:
Constructor called for A1

So the unnecessary copy has not happened.

Related

Populate a vector with literal values

Method 1: Use an array and the range constructor

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

int main()
{
    typedef std::vector<int> intvec;

    int arr[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
    const size_t n = sizeof(arr) / sizeof(int);
    intvec vec1(arr, arr + n);
    
    std::copy(vec1.begin(), vec1.end(), std::ostream_iterator<int>(std::cout, " "));
}

Method 2: Use boost::assign::list_of

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <boost/assign/list_of.hpp>
#include <boost/range/algorithm/copy.hpp>

int main()
{
    typedef std::vector<int> intvec;

    int arr[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
    const size_t n = sizeof(arr) / sizeof(unsigned int);
    
    intvec vec2 = boost::assign::list_of(31)(28)(31)(30)(31)(30)(31)(31)(30)(31)(30);
    
    boost::copy(vec2, std::ostream_iterator<int>(std::cout, " "));
}

Method 3: Use boost::assign

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <boost/assign/std/vector.hpp>
#include <boost/range/algorithm/copy.hpp>
using namespace boost::assign; // bring 'operator+=()' into scope

int main()
{
    typedef std::vector<int> intvec;

    intvec vec3;
    vec3 += 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30;
    
    boost::copy(vec3, std::ostream_iterator<int>(std::cout, " "));
}

Method 4: Use a C++11 initializer

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

int main()
{
    typedef std::vector<int> intvec;

    intvec vec4 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
    
    std::copy(vec4.begin(), vec4.end(), std::ostream_iterator<int>(std::cout, " "));
}

Related

Singletons in C++

The only reason to use the Singleton Design Pattern is when there really must be one and only one instance of a class. If this isn’t the case, you are much better off allowing multiple instantiation and making the instance a member of an application class.

Having said that, below is a standard implementation of Singleton.

class Singleton
{
public:
    static Singleton& getInstance()
    {
        static Singleton instance_;
        return instance_;
    }
private:
    Singleton()
    {
    };
    Singleton(const Singleton&);
    void operator=(const Singleton&);
};

Points to note are:

  1. The single instance is a static variable inside the getInstance() method.
    This means it is instantiated on first use and is guaranteed to be destroyed
  2. The constructor is private so the class cannot be instantiated from outside.
  3. The copy constructor and copy assignment operator are private so the object cannot be copied from the outside.
  4. They do not need to be implemented as they can never be called (except by the Singleton class, which won’t).

If you’re using Boost, rather than declaring the copy constructor and copy assignment operator private, you can derive the class from boost::noncopyable:

#include <boost/core/noncopyable.hpp>
class Singleton : private boost::noncopyable

Reference: noncopyable

In C++11, you can use the new = delete syntax. It can go in the public section:

public:
    Singleton(const Singleton&) = delete;
    void operator=(const Singleton&) = delete;

typedef and using

One of the nicer new features in C++11 is the extension of the using keyword in an alias-declaration so that it is now equivalent to typedef in all cases.

This means that code like this:

template <class T>
class C
{
    typedef typename T::U V;
};

Can be written like this:

template <class T>
class C
{
    using V = typename T::U;
};

Function pointers also look much better:

typedef void(pfn*)(const C&);

Becomes:

using pfn = void(*)(const C&);

Looping over a container in C++

It’s best to use an algorithm when processing a container, or the contents of any pair of iterators, in C++, but it’s good to know how to iterate when you have to.

Here’s the vector we’re going to use:

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

typedef std::vector<int> intvec;

int main()
{  
    intvec v(10);
    std::iota(v.begin(), v.end(), 0);
    iterate(v);
}

Method 1: Use iterators

This is the most familiar interface.

void iterate(const intvec& v)
{
    for (intvec::const_iterator it = v.begin(); it != v.end(); ++it) {
        // Do something with *it
    }
}

Method 2: Use indices

Note that only random access containers like vector and deque support indexed access.

void iterate(const intvec& v)
{
    for (intvec::size_type i = 0; i < v.size(); ++i) {
        // Do something with v[i]
    }
}

Method 3: Use Boost.Foreach

This was the most elegant method until C++11.

#include <boost/foreach.hpp>

void iterate(const intvec& v)
{
    BOOST_FOREACH(intvec::value_type el, v) {
        // Do something with el
    }
}

Reference: Boost.Foreach

Method 4: Use a range-based for loop

This is now the recommended method.

void iterate(const intvec& v)
{
    for (const auto& el: v) {
        // Do something with el
    }
}

nullptr

The nullptr constant is a new addition to C++11 that removes some ambiguity caused by the definition of NULL.

Consider the following code:

#include <iostream>

int f(int)
{
    std::cout << "f(int)" << "\n";
}

int f(void*)
{
    std::cout << "f(void*)" << "\n";
}

int main()
{
    f(NULL); // Ambiguous
    f(0);    // Calls f(int)
}

The first overloaded call is ambiguous because f(NULL) could resolve both to f(void*) and f(int).

The nullptr constant is of type nullptr_t, which can be implicitly converted to void* but the conversion the other way is not allowed.
This allows overloads for both int and void* to work:

int main()
{
    f(nullptr); // Calls f(void*)
    f(0);       // Calls f(int)
}

How to concatenate two vectors in C++

Methods

  1. Use std::vector::insert()
  2. Use std::copy with a std::back_inserter()
  3. Use std::reserve() and then std::copy()
  4. Use std::transform() with std::back_inserter()
  5. Use std::reserve() and then std::transform()

Method 1: Use std::vector::insert()

    vector1.insert(vector1.end(), vector2.begin(), vector2.end());

Method 2: Use std::copy with a std::back_inserter()

    std::copy(vector2.begin(), vector2.end(), std::back_inserter(vector1));

Method 3: Use std::reserve() and then std::copy()

This means that the vector won’t need to be reallocated during the copy, so may be faster.

    vector1.reserve(vector1.size() + vector2.size());
    std::copy(vector2.begin(), vector2.end(), vector1.end());

Method 4: Use std::transform() with std::back_inserter()

This means you can use a functor on the elements of vector2 to modify them or change their type before adding them.

    std::transform(vector2.begin(), vector2.end(), vector1.begin(), transformer());

Method 5: Use std::reserve() and then std::transform()

    vector1.reserve(vector1.size() + vector2.size());
    std::transform(vector2.begin(), vector2.end(), vector1.begin(), transformer());

In all cases you can use the new C++11 std::begin() and std::end() functions to get the beginnings and endings of the vectors.

Related