在C ++中递归查找向量中的最大值

泰国舞

我试图写一个函数来递归地找到向量中的最大值。为此,我想在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_elementC ++数据结构中的max值。

这是一个函数的测试样本,该函数可以在无序向量中递归地获取最大值,而每次迭代都会丢失最后一个元素:

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中进行检查

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用递归 C++ 查找向量中的最大值

C ++-无法读取向量中的最大值

使用溢出和循环在 C 中查找最大值

从C ++中的向量中找出局部最大值/局部最小值(范围)的数量

如何在C ++中获得向量复数值的最大值,最小值和位置?

使用C中的函数查找数组中的最大值和最小值

在处理领带情况的同时查找矩阵中的最大值 [在 C 中]

使用c#在excel中查找每个月的最小值和最大值

在C ++中的向量中查找值

在2D数组C ++中查找每一行的最大值

查找最大值并删除2D数组中的该行。C ++

在C ++中找到const向量中4个最大值的迭代器的最有效方法

浮点比较C ++-查找最大值

查找元组元素的最大值c ++

C ++如何在n个元素的一维数组中查找最小值和最大值?

在C prgram中查找一系列数字的最大值和最小值(我的代码错误)

在 C 中显示数组中的最大值

从 C 中的终端计算最小值/最大值

从C中的数组打印垃圾值而不是最大值

在Scala中递归查找列表中的最大值

如何在二维数组(矩阵)中查找每一行的最大值C#

从 Boost C++ 数组的元素中减去最大值

c-“ writev”中“ iovcnt”参数的允许最大值?

在C#中获取动态类型的最大值

使用递归查找数组中的最大值

使用递归查找数组中的最大值

在python中递归查找具有最大值的元素

使用递归查找数组中的最大值相对

如何在C ++向量(Eigen)中获得最大的n值?