【问题标题】:Beginner's C++: How do I pass a list as a function parameter?初学者的 C++:如何将列表作为函数参数传递?
【发布时间】:2019-04-10 21:04:01
【问题描述】:

我正在尝试为入门级 C++ 函数创建用户生成的搜索函数。该函数应该接受一个列表和三个整数,但它不会识别该列表。我可以传递 int[],但每当我给它一个名称,例如“int[] list”时,它就会关闭程序。

编辑:这是我得到的警告:预期为“)”。然后它检查变量参数名称并说“第一个未识别”,“最后一个未识别”,等等。进行了一些忍者编辑以在此处显示更多代码。对不起!

我觉得这对于 C++ 用户来说非常初级,但我不明白!我还不想在这个程序中使用指针。

int binSearch(int[] first, int target, int first, int last) {
    int middle = (first + last) / 2; 
    cout << "Entering binSearch: list[first]=" + list[first] +
        ", list[last]=" + list[last] + ", "; 
    cout << "list[middle]=" + list[middle];
}

int main() {

     int list[10]; 

    // creating sorted array 
    cout << "The list is "; 
    for (int i = 0; i < 10; i++) {
        list[i] = 2 * i + 1; 
        cout << list[i] + " "; 
    }
    cout << endl; 

    // prompt user to enter key 
    int key; 
    cout << "Enter a key: "; 
    cin >> key; 
    int index = binSearch(list, 10, key, 0, 10 - 1); 
} 

【问题讨论】:

  • 你说的 是什么意思?“给它一个名字,比如“int[] list”,它会抛出程序。”?请提供正确的minimal reproducible example 并包含所有错误消息
  • 使用std::vector
  • 您没有定义程序中的列表,至少就我们所见...正如@UnholySheep 建议的那样,您应该为我们提供更多测试代码
  • 我不确定您的代码中发生了什么。我想你的意思是命名你的数组列表?这可能是一个问题,因为您似乎正在使用命名空间 std 并且列表在该命名空间中
  • 当你说列表时,它对我来说意味着std::list&lt;int&gt;,这可能不是你的意思。相反,听起来你想传递一个数组?

标签: c++ list function


【解决方案1】:

在 C++ 中,数组在变量名后用括号声明:

int binSearch(int list[], int target, int first, int last)

请注意,我还将第一个参数从 first 更改为 list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多