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");
문제
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 c++11 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"};