对键进行排序,并且对与每个键关联的值也进行排序。因此,我们可以认为键值对是排序的。thrust::unique
如果它可以将这 2 个向量视为单个向量,它将直接在此工作。这可以通过使用 . 将每个位置的 2 个项目(键值)压缩到单个元组中来实现zip_iterator
。
以下是如何就地实现这一点,并将键值向量修剪为仅唯一元素:
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;
}