简体   繁体   English

在C ++中,如何为向量中的每个元素创建一个新对象?

[英]In C++ how can I make a new object for every element in a vector?

Suppose I've got this class: 假设我有这个课:

class dog
{
    public:
        //dogstuff
    private:
        //secret dogstuff
};

and then I've got a function that searches through something unrelated and gets me an UNKNOWN NUMBER OF DOG NAMES: 然后,我有了一个搜索不相关内容的函数,并得到了未知数量的狗名:

dogNamesVector = getListOfDogNames();

So, the list of dog names might be something like "Spike, Spot, George, Shadow, ect..". 因此,狗名列表可能类似于“ Spike,Spot,George,Shadow等”。

Is there a smart way to then go: 有什么聪明的方法可以去:

dog DOGNAME()

and get a bunch of dog objects that I can call and use with the list of dog names? 并获得一堆我可以调用并与狗名列表一起使用的dog对象?

So, lets say you have a vector of dogs: 因此,假设您有一条狗向量:

    vector<dog> dogs {...};

And we will assume that there are already dogs in this vector. 我们将假定此向量中已经有狗。 That would mean that you already have objects of type dog, and to call them, all you would need to do is use the bracket notation: 这意味着您已经拥有了dog类型的对象,要调用它们,您需要做的就是使用方括号表示法:

    dogs[i];

If you wanted to assign this dog to another object, you would use: 如果要将此狗分配给另一个对象,则可以使用:

    dog spike = dogs[i];

If you wanted a unique name (key, or identifier) you would include that in the class itself, as such: 如果您想要一个唯一的名称(键或标识符),则可以将其包括在类本身中,如下所示:

    private:
        string dog_name;

And to access that, you would make a member function (or 'method'). 要访问它,您将创建一个成员函数(或“方法”)。 Combine any of these steps with some form of loop (any form of iteration will do) and you can create as many dog objects as needed, and you can also create a function to search by name if that's something that would help you. 将这些步骤中的任何一个与某种形式的循环结合起来(任何形式的迭代都可以),您可以根据需要创建任意数量的dog对象,并且如果可以帮助您,还可以创建一个函数来按名称搜索。

If you have a list of strings, and your dog class can be constructed with a string as input, you can construct a vector of dog objects using iterators to the string list, eg: 如果您有一个字符串列表,并且可以使用字符串作为输入来构造您的dog类,则可以使用迭代器到字符串列表来构造dog对象的向量,例如:

class dog
{
public:
    dog(const std::string name) : m_name(name) {}
private:
    std::string m_name;
};

std::vector<std::string> dogNames = getListOfDogNames();

std::vector<dog> dogs(dogNames.begin(), dogNames.end());

Demo 演示版

std::vector<dog> dogs = get_dogs();
std::vector<std::string> dog_names;

dog_names.reserve(dogs.size());

std::transform(std::begin(dogs), std::end(dogs), std::back_inserter(dog_names), [](auto const& dog) { return dog.name(); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM