【问题标题】:Is there any C++ STL function to process i and i+1 elements?是否有任何 C++ STL 函数来处理 i 和 i+1 元素?
【发布时间】:2022-08-17 20:29:22
【问题描述】:

目前我的代码是这样的

std::vector<int> listOfItems;
for(int i=0; i<listOfItems.size()-1; i++)
{
   doSomething(listOfItems.at(i), listOfItems.at(i+1);
}

我想知道是否可以避免使用此代码并使用任何 STL 算法以获得更好的可读性。 谢谢

  • 可能是std::for_each 之类的东西?
  • 但我认为对于每个你一次只能处理一个元素,不是吗?
  • 正确的。但是您的可变 lambda 只是为循环的下一次迭代保存每个值(并且除了第一次调用它之外不做任何事情)。
  • 可以使用std::adjacent_find 但不要。除了i 应该是std::size_t 而不是int 之外,您的循环没有任何问题。您还需要确保在循环开始之前您的向量不为空。
  • 代码有一个bug,因为当listOfItems为空时listOfItems.size()-1会有一个非常大的值。因此,您需要在运行循环之前进行检查。一旦你明白了,不要在listOfItems.at(i)listOfItems.at(i+1) 上浪费时间;你知道ii+1 是有效的索引。只需使用listOfItems[i]listOfItems[i+1]

标签: c++ stl


【解决方案1】:

我的实用程序库中有这个。随意使用它:

/** Iterates over each adjacent pair of the range.
 *
 * For the sequence [1, 2, 3, 4], it invokes fn(1, 2), fn(2, 3), fn(3, 4).
 * Nothing is invoked if the sequence is only one element long.
 *
 * @returns The final state of fn.
 */
template <typename FwdIt, typename BinFn>
BinFn for_pairs(FwdIt first, FwdIt last, BinFn fn) {
  if (first == last) {
    return fn;
  }

  for (FwdIt it = std::next(first); it != last; ++first, ++it) {
    fn(*first, *it);
  }

  return fn;
}

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 2013-08-27
    • 2022-01-10
    • 1970-01-01
    • 2014-12-12
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    相关资源
    最近更新 更多