gpt4 book ai didi

c++ - 在 C++ 中递归地查找 vector 中的最大值

转载 作者:行者123 更新时间:2023-12-02 04:37:04 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来递归地查找 vector 中的最大值。为此,我想在 findMax 函数中测试它是否可以返回列表中的最后一个值。但最后,当列表只有一个元素时,它返回变量的地址而不是值。这是为什么?

/// finding max value in a list recursively
template <typename T>
int findMax(std::vector<T> arrayVector)
{
if(arrayVector.size()==1)
{
return arrayVector[0];
}

int op1= arrayVector[0];
std::vector<T> newVector (arrayVector.cbegin() + 1, arrayVector.cend());
disPlay(newVector);
int op2= findMax(newVector);

}


/// print vector
template <typename T>
void disPlay(std::vector<T> vectorArray)
{
for (int i=0; i< vectorArray.size(); i++)
{
std::cout << vectorArray[i] << "\t";
}
std::cout << "\n";
}



main()
{
std::vector<int> arrayVector = {6, 8, 19, 20, 23, 41, 49, 53, 56};

std::cout << findMax(arrayVector) << endl;
return 0;
}

最佳答案

我运行了你的程序,它触发了几个警告,其中一个可能证明不需要的行为是合理的,那就是 int findMax(std::vector<T> arrayVector) 中缺少返回值。 .

template <typename T>
int findMax(std::vector<T> arrayVector)
{
if(arrayVector.size()==1)
{
return arrayVector[0];
}

int op1= arrayVector[0];
std::vector<T> newVector (arrayVector.cbegin() + 1, arrayVector.cend());
disPlay(newVector);
int op2= findMax(newVector);
return op2; //<-- added return
}

我纠正了https://wandbox.org/permlink/Kts9qs7MooG4dEQL中的问题

现在看来还可以。

使用编译器警告,它可以节省你大量的时间和头痛。

现在,这解决了您的代码问题,但我建议使用 std::max_element 获取 C++ 数据结构中的最大值。

这是一个函数的测试示例,用于在无序 vector 中递归获取最大值,但会在每次迭代中丢失最后一个元素:

template <typename T>
void findMax(std::vector<T>& arrayVector)
{
if(arrayVector.size() == 0) //stop condition
return;

int max = *std::max_element(arrayVector.begin(), arrayVector.end());
std::cout << "Max value: "<< max << std::endl;
arrayVector.erase(arrayVector.end() - 1); //last element being deleted in every recursion

findMax(arrayVector);
}

查看https://wandbox.org/permlink/0oyGnXoQdwhl3kUJ

关于c++ - 在 C++ 中递归地查找 vector 中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60159356/

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