gpt4 book ai didi

c++ - std::unique 合并

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:53:19 25 4
gpt4 key购买 nike

我正在使用 std::unique 使用具有大 epsilon 的 equals 方法在浮点 vector 中获取合并簇。问题是它像 1 一样运行并将它们变成 2。
虽然我希望它像在“相等”点上使用平均值一样合并它们,但将它们变成 3。

(1) ...               .      ....    .....
(2) . . . .
(3) . . . .

如何使用 C++ 标准库执行此操作?

最佳答案

不,没有标准算法可以满足您的需求。然而,它并不是非常复杂。我试图对迭代器做出最少的假设,因此这应该适用于任何前向输入迭代器。

#include <iostream>

template<class initer, class outiter, class predicate>
outiter average_runs(initer begin, initer end, outiter out, predicate pred) {
//quit if no range
if (begin == end)
return out;
initer endrun = begin;
do {
//find end of run
while(endrun+1 != end && pred(*endrun,*(endrun+1)))
++endrun;
//move "begin" to the middle
std::advance(begin, std::distance(begin,endrun)/2);
//output the result
*out++ = *begin;
//start next run
begin = ++endrun;
} while(endrun != end);
return out;
}

bool intclose(int l, int r)
{ return r-l <= 1;}
int main() {
int array[13] = {1,2,3,20,25,26,27,28,35,36,37,38,39};
int output[13] = {};
int* end = average_runs((int*)array, array+13, (int*)output, &intclose);
for(int* c = output; c<end; ++c)
std::cout << *c << ' ';
return 0;
}
//displays: 2 20 26 37

关于c++ - std::unique 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7842580/

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