gpt4 book ai didi

c++ - 在 C++ 中使用未声明的列表作为参数

转载 作者:行者123 更新时间:2023-11-30 05:21:19 25 4
gpt4 key购买 nike

最近通过完成 checkio.org 的“任务”开始学习 C++。我现在的主要问题是验证解决方案,所以我想像这样使用 assert() :

assert(index_power({1, 2, 3, 4}, 2) == 9);

问题是我总是收到错误提示:

error: cannot convert ‘<brace-enclosed initializer list>’ to ‘int*’ for argument ‘1’ to ‘int index_power(int*, int)’  
assert(index_power({1, 2, 3, 4}, 2) == 9);

有没有办法将未声明的数组作为函数参数传递,或者每次我想像这样使用断言时都必须声明新数组??

最佳答案

在这里,您现在有一个大括号括起来的初始化程序列表:

assert(index_power({1, 2, 3, 4}, 2) == 9);

列表是:{1, 2, 3, 4} 。要允许这个大括号括起来的初始化列表,你需要使用允许这个方法的库。例如 std::vector。所以你可以改变你的论点:

int index_power(int* args, int num);

int index_power(std::vector<int>, int num);

如果您对如何制作自定义的大括号封闭初始化构造函数感兴趣,您可以使用 std::initalizer_list:

MyClass(std::initializer_list<int> li) {
std::vector<int> v(li);
}

你可以看到更多关于std::initalizer_list here .

关于c++ - 在 C++ 中使用未声明的列表作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com