Saturday, 16 April 2011

Create string on the fly just in one line

We often make use of std::stringstream to convert values of various types into a single std::string. For example, see this:

std::stringstream ss;
ss << 25 << " is greater than " << 5;
std::string s = ss.str(); //s => "25 is greater than 5"

Paul (at stackoverflow) was trying to think of a clever way to concatenate various things into a single string without having to use an ostringstream explicitly. He came up with a macro which he didn't like though.

Sunday, 10 April 2011

Calculating size of arrays - one dimensional and multiple dimensional

Someone asked at stackoverflow : How to get size of an array using metaprogramming?

My solution:

For one dimensional arrays,

template<typename T, size_t N>
size_t size_of_array(T (&)[N])
{
   return N;
}

Elegant ways to tokenize strings


Last night I posted a solution at stackoverflow. The question was : what is the right way to split a string into a vector of strings. Delimiter is space or comma.

This is what I first came up with, for space separated string: