Use boost list_of if You Can’t Have Uniform Initialization Yet


In which I demonstrate how boost::assign::list_of simplifies initialization of containers.

I have previously blogged about how Uniform Initialization Simplifies Testing. In C++, you can initialize an array when defining it, but you can not initialize containers:

	int a[] = {1, 2, 3}; //OK
	vector<int> v = {1, 2, 3}; //Not OK

You have to resort to something like this:

	//Either
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);

	//Or
	int tmp[] = {1, 2, 3}; 
	vector<int> v2(tmp, tmp+3);

In C++0X, we will have Uniform Initialization to take care of this, but if you are not on a supported compiler yet, you can use boost::assign while you are waiting:

	vector<int> v3 = boost::assign::list_of(1)(2)(3);

This is, again, especially useful in testing. To translate the example from my last post from C++0X to C++98 with boost:

using boost::assign::list_of;
 
int count_sheep(const vector<string>& animals) {
	return count(animals.begin(), animals.end(), "sheep");
}
 
TEST(TestCountSheep, returns_zero_when_there_are_no_sheep) {
	ASSERT_EQ(0, count_sheep(list_of("pig")("cow")("giraffe"))); //here
}
	 
TEST(TestCountSheep, returns_all_sheep) {
	ASSERT_EQ(2, count_sheep(list_of("sheep")("cow")("sheep"))); //and here
}

To use boost::assign, make sure to #include <boost/assign.hpp>. It has other clever tricks as well, so be sure to check out the docs. Boost is a widely used collection of high quality libraries for C++, and can be downloaded here.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

Compiling Boost with STLPort on Windows


I couldn’t find a concise howto on compiling Boost with STLPort on Windows, so here it is:

  1. Download Boost. I used version 1.44, I have heard people have struggled with earlier versions.
  2. In the Boost root directory, open project-config.jam. Add the following line:
    using stlport : STLPORT_VERSION : C:/PATH_TO_STLPORT/stlport : C:/PATH_TO_STLPORT/lib ;
    , substituting STLPORT_VERSION for you version of STLPort, and PATH_TO_STLPORT to you STLPort directory.
  3. Build Boost: bjam stdlib=stlport stage. If you want to build a static lib, add link=static runtime-link=static.

My setup:

  • Boost 1.44
  • STLPort 5.2.1
  • Visual Studio 2008

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter