gpt4 book ai didi

c++ - 没有运算符 "<<"匹配这些操作数(可变长度数组)

转载 作者:行者123 更新时间:2023-11-28 07:01:09 25 4
gpt4 key购买 nike

我在 C++ 类(class)中遇到编码作业问题。赋值要求我们有调用函数的可变长度数组。每当我尝试将函数调用到 main 中时,我总是在标题中收到错误。我见过其他类似的问题,但我似乎无法在我自己的程序中找到解决这些问题的答案。

    `# include <iostream> //Allows user input
using namespace std;

int i, hold; //Global variables for use in functions and loops through-out the program.
//Functions below main.

int main()
{
int length=0;
int* a = new int[length];; //This array has 'length' spaces.
cout << "How many numbers would you like to sort?\n";
cin >> length;
for(i=0;i<length;i++) //This loop populates the array.
{
cout << "Enter a number.\n";
cin >> a[i];
}
cout << "This doesn't work ->" << sortDescending(a, length) << endl;
cout << "This also doesn't work" << shiftRight(a, length) << endl;
return 0;
}

这里是函数本身。

    void sortDescending(int a[], int length) //Sorts the numbers in the array in descending order.
{
for(i=0;i<length;i++)
{
if(a[i]<a[i+1]) //Detects if the first number is smaller than the second.
{ //If the first is smaller than the second then this swaps them.
hold=a[i];
a[i]=a[i+1];
a[i+1]=hold;
}

}
}

void shiftRight(int a[], int length)
{
for(i=0;i<length;i++)
{
a[length-i]=a[length-(i-1)];
}
}

最佳答案

sortDescending()shiftRight() 这两个函数都是void 返回函数。返回 void 的函数没有 return 语句,因此无法从调用中获取任何值。因此,尝试“打印”以下代码中函数的返回值总是会失败:

... << sortDescending(a, length) << ...
... << shiftRight(a, length) << ...

我将采取一个步骤,假设您正在尝试打印实际数组。这可以在调用函数后使用 for 循环简单地完成:

sortDescending(a, length);
std::cout << "After sortDescending(): ";

for (int i = 0; i < length; ++i)
{
std::cout << a[i] << " ";
}
std::cout << std::endl;

shiftRight(a, length);
std::cout << "After shiftRight(): ";

// Do the same as the above

为了更方便,您甚至可以在这两个函数中打印数组。但这是我将留给你的任务。 :)

关于c++ - 没有运算符 "<<"匹配这些操作数(可变长度数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22445320/

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