gpt4 book ai didi

c++ - 将一系列已排序元素划分为相邻的组

转载 作者:行者123 更新时间:2023-11-28 04:32:31 24 4
gpt4 key购买 nike

我在下面有一个排序的项目列表。我需要确定如何从此列表中挑选 [inclusive, exclusive) 项目对,以便它们之间的差异超过某个固定值(例如下面示例中的 5)。

因此,这应该导致将列表划分为相邻的范围(没有遗漏任何元素)。

我想出了一个蛮力的方法来做到这一点( see live COLIRU demo ),但我确信必须有一个更优雅的解决方案,我可能遗漏了一些边缘情况(例如 1 a包含单个值的列表应该导致空对)。我在想 STL 范围算法的一些变体,std::adjacent_findstd::lower_bound/std::upper_bound 的组合可用于确定这些包容性/exclusive 对 - 例如在循环或某种形式中使用或某些基于范围的搜索 - 但我无法弄清楚。

实时搜索值 { 100, 104, 108, 112, 116, 120 } 导致以下非重叠范围。请注意,最后一对(差值为 4(即 < 5)是一种特殊情况(请参见代码)。

[100,104),[108,112),[116,120)

执行此操作的代码如下:

#include <iostream>
#include <algorithm>
#include <experimental/iterator>
#include <string>
#include <vector>

int main()
{
std::vector<int> elements = { 100, 104, 108, 112, 116, 120 };
std::vector<std::pair<int, int>> result;
auto current = elements.begin();
while (current != std::prev(elements.cend())) {
auto next = std::next(current);
while (((*next - *current) < 5) && (next != std::prev(elements.cend()))) {
++next;
}
// consider edge case where we are at the end of the list
if (next != std::prev(elements.cend())) {
result.emplace_back(*current, *std::prev(next));
} else {
result.emplace_back(*current, *next);
}
current = next;
}
std::transform( result.cbegin(), result.cend(), std::experimental::make_ostream_joiner(std::cout, ","),
[](const auto& next){ return std::string("[") + std::to_string(next.first) + ',' + std::to_string(next.second) + ')'; } );
}

最佳答案

auto next = std::next(current);
while (((*next - *current) < 5) && (next != std::prev(elements.cend()))) {
++next;
}

在一个已排序列表中,我们正在寻找第一个元素至少比当前元素大 5 对吗?这正是std::lower_bound是为了 - 它进行二进制搜索而不是线性搜索:

auto next = std::lower_bound(std::next(current), elements.end(), *current + 5);

将其与修复循环条件相结合,直到列表的结束,而不是结束之前的一个(这只是......看起来不对,需要一些严肃的理由),以及整个 body 可以只是:

while (current != elements.end()) {
auto next = std::lower_bound(std::next(current), elements.end(), *current + 5);
result.emplace_back(*current, *std::prev(next));
current = next;
}

旁注。这:

std::transform( result.cbegin(), result.cend(), std::experimental::make_ostream_joiner(std::cout, ","),·
[](const auto& next){ return std::string("[") + std::to_string(next.first) + ',' + std::to_string(next.second) + ')'; } );

对我来说似乎没有比这个更好的了:

bool first = true;
for (auto const& [first, second] : result) {
if (!first) std::cout << ',';
first = false;
std::cout << '[' << first << '',' << second << ']';
}

YMMV。我知道人们喜欢说“没有原始循环”,但我很少看到 transform 导致可读代码....

关于c++ - 将一系列已排序元素划分为相邻的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52485118/

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