C++当类型T需要构造函数时,是否可以创建类型为T的std :: list?

loo*_*oop 0 c++ stl std stdlist

例如:

class apple
{
public:
    string name;

    apple::apple(string name) : name(name)
    {
    }
};
Run Code Online (Sandbox Code Playgroud)

如果我想制作一堆每个都有苹果类型的列表,我想我可以做类似的事情std::list<apple> empire("empire"), macintosh("macintosh").基本上我想为list<T>我创建列表时声明的类T的构造函数传递参数.对不起,如果我没有解释这个问题,如果你有这种能力,请随时编辑我的问题.

谢谢

编辑这个问题似乎令人困惑,这可能是因为我给出了一个糟糕的例子.我需要重新设计我的课程.按照这个例子,虽然我想要的是一个列表,它都是帝国苹果,该列表中的每个苹果都有一个指定类型的帝国,一个列表都是macintosh苹果,该列表中的每个苹果都有一个指定类型的macintosh.

因此,为了澄清一些或在此处混淆一些我们去.

class apple
{
public:
    string variety_name;
    string description;
    apple::apple(string variety_name, string description)
        : variety_name(variety_name), description(description)
    {
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    // Vlad from Moscow's answer
    std::list<apple> empire(1, apple("empire", "picked yesterday")),
        macintosh(1, apple( "macintosh", "picked yesterday")); 

    // Vaughn Cato's answer
    empire.push_back(apple("empire", "picked today"));
    macintosh.push_back(apple("macintosh", "picked today"));

    for(list<apple>::iterator it=empire.begin(); it != empire.end(); ++it)
    {
        cout << it->variety_name << " " << it->description << endl;
    }

    for(list<apple>::iterator it=macintosh.begin(); it != macintosh.end(); ++it)
    {
        cout << it->variety_name << " " << it->description << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以看到,一次而不是每次存储品种会更容易; 我的班级显然需要重新设计,但这并不能使答案变得不那么有效.大家都感谢你的帮助

yur*_*hek 6

当然,您可以使用emplace(),emplace_front()emplace_back()使用适当的构造函数就地构造对象:

std::list<apple> list;
list.emplace(list.end(), "one");
list.emplace_front("two");
list.emplace_back("three");
Run Code Online (Sandbox Code Playgroud)