Search code examples
c++liststdlist

Is it possible to create a std::list in one line, specifying its values (c++)?


I want to create a std::list by specifying its values, and I'd like to do it in one line, eg :

std::list<std::string> myList("Cat", "Dog", "Pig"); // doesn't compile

I couldn't find a way to do it simply with std::list (I'm not satisfied with c++ reference's examples), have I missed something? If it's not possible with standard lists, is there a reason? And then what is the simplest way to implement it?

Thanks in advance.


Solution

  • In C++11 you can use initializer:

    std::list<std::string> t { "cat", "dog" };
    

    In C++03 boost::assign::list_of is available:

    #include <boost/assign/list_of.hpp>
    
    std::list<std::string> t = boost::assign::list_of("cat")("dog");