用矢量调用函数

Calling Functions with Vectors

本文关键字:函数 调用      更新时间:2023-10-16

我仍然是C++的初学者,但我在编码方面遇到了一些麻烦。

我已经定义了函数void AskMenuChoice(vector&choice,int*pIndex),但我不知道调用Main.cpp的正确语法。

有人知道如何尽可能简单地解释这一点吗?谢谢

我假设您希望通过参数pIndex返回所选索引,在这种情况下,您需要在调用函数中创建一个整数,并将此变量的地址传递给此函数。

std::vector<Choice> choices = /* however you're making your choices */;
int chosen;
AskMenuChoice(choices, &chosen);
std::cout << "Option " << chosen << " was picked." << std::endl;

不过,这样做有点尴尬,最好AskMenuChoice返回值。这将把函数的签名改为int AskMenuChoice(vector& choices),用法改为:

std::vector<Choice> choices = /* however you're making your choices */;
int chosen = AskMenuChoice(choices);
std::cout << "Option " << chosen << " was picked." << std::endl;