문제

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.

도움이 되었습니까?

해결책

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");

다른 팁

Use Boost.Assign.

#include <boost/assign/list_of.hpp>     
std::list<std::string> test = boost::assign::list_of("abc")("def");

In use an initializer

std::list<std::string> test { "abc", "def" };

in c++11 you can write

std::list<std::string> foo = { "bar", "meh", "bah" };

you'd need an up to date compiler for that. (ie gcc 4.8)

Otherwise there is no possibility in c++.

std::list<std::string> myList { "Cat", "Dog", "Pig"};

C++11 only. For older C++ refer to Boost.Assign.

using boost::asign::list_of;

std::list<std::string> myList = list_of("Cat")("Dog")("Pig");

In C++11 you can do this using uniform initialization:

std::list<std::string> myList{"Cat", "Dog", "Pig"};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top