c++ max_element 每n个元素

标签 c++ boost std

有没有办法找到容器中比较每 N 个元素的最大元素并返回索引。使用 STL、BOOST 或...其他库?

对于每个 N,我的意思是使用 std::max_element,但将 for 的增量从++first 更改为 first += n;

// based on std::max_element

#ifndef NEWTON_ALGORITHM_SEARCH_MAX_INDEX_HPP
#define NEWTON_ALGORITHM_SEARCH_MAX_INDEX_HPP

#include <iterator>

#include <newton/functional.hpp>

namespace newton {

  // SAME THAT STD::MAX_ELEMENT
  template<class ForwardIt, class Compare>
  const ForwardIt max_index(ForwardIt first, ForwardIt last, Compare comp)
  {

    if ( newton::equal(first, last) ) // newton::equal is basically equivalent to std::equal_to
      return last;

    ForwardIt largest = first;
    while ( newton::not_equal(++first, last) )
      if (comp(*largest, *first))
        largest = first;

    return largest;

  }

  // possible names
  // max_index_some
  // max_index_every_n
  // max_index__n

  template<class ForwardIt, class Size, class Compare>
  const ForwardIt max_index_every_n(ForwardIt first, ForwardIt last, Size n, Compare comp)
  {

    if ( newton::equal(first, last) )
      return last;

    ForwardIt largest = first;
    Size blocks = std::distance(first, last) / n; // integer blocks

    if ( newton::greater_equal(blocks, 1) ) {

      // if there are exacly N elements, can't sum example
      // v.size() = 10, first start in 0, so "0 += 10" is "10", but last index is "9"
      // but if mod >= 1, then index is at least 10, so can sum

      if ( newton::greater_equal( std::distance(first, last) % n, 1) ) {
        for (size_t i = 1; newton::less_equal(i, blocks); ++i, first += n) {

          if (comp(*largest, *first))
            largest = first;
        }
      }
      else {

        for (size_t i = 1; newton::less(i, blocks); ++i, first += n) {

          if (comp(*largest, *first))
            largest = first;
        }

      }

    }

    return largest;

  }

  template<class ForwardIt>
  const ForwardIt max_index(ForwardIt first, ForwardIt last)
  {
    return max_index(first, last, newton::structure::less());
  }
} // newton

如果没有,您的解决方案是什么,尝试将其包含在下一个 STL 版本中。 remember

最佳答案

range-v3 ,这将是:

auto r = v | ranges::view::stride(n);
auto it = ranges::max_element(r);

关于c++ max_element 每n个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49824956/

相关文章:

c++ - 在 Visual C++ 2010 上哪个更快 - std::shared_ptr 或 boost::shared_ptr?

c++ - 共享内存的 boost 容器是否实现锁定?

c++ - STL 容器的范围插入函数在 c++11 下返回 void?

c++ - boost::bind 何时将参数转换为所需的类型?

c++ - 字符串中的十六进制到整数中的十六进制

c++ - 在 shared_ptr 中包装一个不透明的指针

c++ - cmath 中的 pow() 实现和高效替换

客户端/服务器之间的 C++/Winsock TCP 发送/接收问题

c++ - 如何在 C++ 中使用模板避免重复代码

c++ - 为什么我的 Qt Widget 没有显示?