gpt4 book ai didi

cuda - 推力:删除键值数组中的重复项

转载 作者:行者123 更新时间:2023-12-01 13:01:43 25 4
gpt4 key购买 nike

我有一对大小相等的数组,我将它们称为键和值。

例如:

K: V
1: 99
1: 100
1: 100
1: 100
1: 103
2: 103
2: 105
3: 45
3: 67

键被排序,与每个键关联的值是
排序。我该怎么做 删除 重复 与每个键相关联
及其相应的键?

也就是说,我想将上述内容压缩为:
1: 99
1: 100
1: 103
2: 103 <-- This should remain, since key is different
2: 105
3: 45
3: 67

我看了 流压缩 中可用的功能推力 , 但
无法找到任何可以做到这一点的东西。这可能与
推力?还是我需要编写自己的内核来标记重复项
一个模板,然后删除它们?

最佳答案

键被排序并且与每个键关联的值也被排序。因此,我们可以认为 键值对 排序。 thrust::unique如果它可以将这两个向量视为单个向量,则将直接对此进行处理。这可以通过使用 zip_iterator 将每个位置的 2 个项目(键值)压缩成一个元组来实现。 .

这是就地实现这一点并将键值向量修剪为仅唯一元素的方法:

typedef thrust::device_vector< int >                IntVector;
typedef IntVector::iterator IntIterator;
typedef thrust::tuple< IntIterator, IntIterator > IntIteratorTuple;
typedef thrust::zip_iterator< IntIteratorTuple > ZipIterator;

IntVector keyVector;
IntVector valVector;

ZipIterator newEnd = thrust::unique( thrust::make_zip_iterator( thrust::make_tuple( keyVector.begin(), valVector.begin() ) ),
thrust::make_zip_iterator( thrust::make_tuple( keyVector.end(), valVector.end() ) ) );

IntIteratorTuple endTuple = newEnd.get_iterator_tuple();

keyVector.erase( thrust::get<0>( endTuple ), keyVector.end() );
valVector.erase( thrust::get<1>( endTuple ), valVector.end() );

如果要压缩并生成单独的结果流,则需要为您的类型编写自己的二进制谓词,该谓词查看元组的两个元素。 thrust::zip_iterator可用于从单独的数组形成虚拟元组迭代器。

一个完整的工作示例如下所示:
#include <iostream>
#include <thrust/tuple.h>
#include <thrust/functional.h>
#include <thrust/device_vector.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/unique.h>

// Binary predicate for a tuple pair
typedef thrust::tuple<int, int> tuple_t;
struct tupleEqual
{
__host__ __device__
bool operator()(tuple_t x, tuple_t y)
{
return ( (x.get<0>()== y.get<0>()) && (x.get<1>() == y.get<1>()) );
}
};

typedef thrust::device_vector<int>::iterator intIterator;
typedef thrust::tuple<intIterator, intIterator> intIteratorTuple;
typedef thrust::zip_iterator<intIteratorTuple> zipIterator;
typedef thrust::device_vector<tuple_t>::iterator tupleIterator;

int main(void)
{
thrust::device_vector<int> k(9), v(9);
thrust::device_vector<tuple_t> kvcopy(9);

k[0] = 1; k[1] = 1; k[2] = 1;
k[3] = 1; k[4] = 1; k[5] = 2;
k[6] = 2; k[7] = 3; k[8] = 3;

v[0] = 99; v[1] = 100; v[2] = 100;
v[3] = 100; v[4] = 103; v[5] = 103;
v[6] = 105; v[7] = 45; v[8] = 67;

zipIterator kvBegin(thrust::make_tuple(k.begin(),v.begin()));
zipIterator kvEnd(thrust::make_tuple(k.end(),v.end()));
thrust::copy(kvBegin, kvEnd, kvcopy.begin());

tupleIterator kvend =
thrust::unique(kvcopy.begin(), kvcopy.end(), tupleEqual());

for(tupleIterator kvi = kvcopy.begin(); kvi != kvend; kvi++) {
tuple_t r = *kvi;
std::cout << r.get<0>() << "," << r.get<1>() << std::endl;
}

return 0;
}

关于cuda - 推力:删除键值数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5521091/

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