传递vector的新实例

C++ Pass a new instance of vector

本文关键字:实例 新实例 vector 传递      更新时间:2023-10-16

我正在准备一门课的期中考试。我需要初始化一个常量数组的对象,以一个向量作为构造函数参数。基本上,我想做一些类似于以下Java代码的事情:

final Pizza[] standardMenu = {
    new Pizza(Arrays.asList(new Integer(1), new Integer(2), new Integer(3))),
    new Pizza(Arrays.asList(new Integer(4), new Integer(5), new Integer(6)))};

除了Integer实例,我将传递Ingredient实例。在c++中有这样的方法吗?我的书和快速的谷歌搜索都没有得到任何好的结果。

我现在正在看的代码(c++):

Ingredient standardIngredients[8] = {Ingredient("American Cheese", "Cheese that comes from America", 1.0), Ingredient("Swiss Cheese", "Cheese that is Swiss", 1.0),
                    Ingredient("Peperoni", "Does it need a description?", 2.0), Ingredient("Ground Beef", "Ground up beef", 3.0),
                    Ingredient("Onion", "Its a vegetable", 0.5), Ingredient("Black Olives", "Olives that possess the color of blackness", 0.5),
                    Ingredient("Jalapenios", "Spicy things", 0.5), Ingredient("Pickles", "Just because I can", 0.5)};
Pizza standardMenu[1] = {Pizza({standardIngredients[0], standardIngredients[1]}, "A string", 7.8)};

这对我有用:

class Pizza
{
private:
    std::vector<int> m_members;
public:
    Pizza(std::vector<int> &members) : m_members(members)
    {
    }
};
const Pizza pizzaArray[] = { Pizza(std::vector<int>{1, 2, 3}),
                             Pizza(std::vector<int>{4, 5, 6}), };

是否可以这样帮助:

typedef vector<string> Pizza; 
auto menu = vector<Pizza>{ Pizza{ "chorizo", "tomato", "pepperoni" }, 
                           Pizza{ "Ananas", "Ham" } };

或者如果你喜欢数组形式的菜单:

Pizza menu[] = { Pizza{ "chorizo", "tomato", "pepperoni" }, Pizza{ "Ananas", "Ham" } };

当然,这是第一步,因为在这个模型中,Pizza只是各部分的总和。如果你想增加更多的信息,比如披萨的价格、卡路里等,最好有一个专门的课程。

编辑:

根据你方补充的资料,我建议以下分类:

class Ingredient {
    string name;
    string description;
    double price;
public:
    Ingredient(string n, string d, double p) : name(n), description(d), price(p) {}
};
class Pizza {
    vector<Ingredient> ingredients; 
    string name; 
    double price; 
public:
    Pizza(vector<Ingredient>i, string n, double p) : ingredients(i), name(n), price(p) {}
};

您的初始化将使用它。

您可以为Pizza定义一个构造函数,它将Ingredient的向量作为参数,或者为Pizza定义一个initializer_list以节省一些输入。

还要注意std::array的使用。在大多数情况下,你不应该再使用c风格的数组,STL容器做了一些很好的事情,比如记住它们的大小。

#include <iostream>
#include <vector>
#include <array>
#include <initializer_list>
using namespace std;
class Ingredient {};
class Pizza {
public:
    Pizza(initializer_list<Ingredient> l) : ing{l} {}
    Pizza(vector<Ingredient> l) : ing{l} {}
private:
    vector<Ingredient> ing;
};
int main()
{
    const array<Pizza, 3> pizzas1 {
        Pizza{Ingredient{}, Ingredient{}, Ingredient{}},
        Pizza{Ingredient{}, Ingredient{}, Ingredient{}},
        Pizza{Ingredient{}, Ingredient{}, Ingredient{}}
    };
    const array<Pizza, 3> pizzas2 {
        Pizza{vector<Ingredient>{Ingredient{}}},
        Pizza{vector<Ingredient>{Ingredient{}}},
        Pizza{vector<Ingredient>{Ingredient{}}}
    };
}