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.

4 Responses to “Use boost list_of if You Can’t Have Uniform Initialization Yet”

  1. janani Says:

    A nice example… How can i assign a vector of objects

  2. janani Says:

    thank you… that works..


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: