如何将一组结构传递给函数?

时间:2013-12-04 23:33:19

标签: c++

假设我们有:

struct elements{
    string drink_name;
    double price_per_can;
    double number_in_machine;
};

struct elements machine[6];

机器填充在main()中。如何将机器传递给函数(通过引用)以在函数内部使用?

2 个答案:

答案 0 :(得分:5)

您可以将其作为参考传递:

void foo(elements (&x)[6])
{
    x[1].price_per_can = 1.8;
    x[4].drink_name = "mom's breakfast juice";
}

int main()
{
    elements machine[6];
    foo(machine);
}

答案 1 :(得分:1)

std::array<elements, 6> machine_c2;

// Edit: Removed const
// Edit: Reflect edit by other user
//        and add consistency with machine.begin()
void doSomething(std::array<elements, 6>& machine) {
    std::cout << machine.begin()->drink_name;
    machine.begin()->drink_name = "Cherry";
}

int main() {
    machine_c2.begin()->drink_name = "Strawberry";
    doSomething(machine_c2);
    std::cout << machine_c2.begin()->drink_name;
    return 0;
}