【问题标题】:std::max with a dynamic array带有动态数组的 std::max
【发布时间】:2017-04-18 17:27:33
【问题描述】:

我正在尝试尽可能多地使用 std 库,但我对 std::max 有疑问

#include <algorithm>

void foo(size_t elem)
{
  auto testArray = new double[elem];
  for(int i = 0; i < elem; ++i)
  {
    testArray[i] = i;
  }

  auto maxElem = std::max(testArray, testArray + (elem - 1));
  delete[] testArray;
}

在这里将参数传递给 std::max 函数的最佳方法是什么?我希望我能让这个数组表现得像一个带有模板的迭代器。

【问题讨论】:

  • 应该是testArray + elem,而不是testArray + (elem - 1)
  • 我用 + elem 试过了,但我得到了一些意想不到的行为。它每次都选择最后一个元素,它不是最大的,但它是最负的。

标签: c++ dynamic standard-library


【解决方案1】:

应该是max_element(),而不是max()

auto maxElem = *(std::max_element(testArray, testArray + elem));

【讨论】:

    猜你喜欢
    • 2014-03-23
    • 2022-07-06
    • 2019-04-05
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多