请考虑下面的简单代码:
thrust::device_vector<int> positions(6);
thrust::sequence(positions.begin(), positions.end());
thrust::pair<thrust::device_vector<int>::iterator, thrust::device_vector<int>::iterator > end;
//copyListOfNgramCounteachdoc contains: 0,1,1,1,1,3
end.first = copyListOfNgramCounteachdoc.begin();
end.second = positions.begin();
for(int i =0 ; i < numDocs; i++){
end= thrust::unique_by_key(end.first, end.first + 3,end.second);
}
int length = end.first - copyListOfNgramCounteachdoc.begin() ;
cout<<"the value of end -s is: "<<length;
for(int i =0 ; i< length ; i++){
cout<<copyListOfNgramCounteachdoc[i];
}我原以为这段代码的输出是0,1,1,3;但是,输出是0,1,1。有人能告诉我我错过了什么吗?注意:copyListOfNgramCounteachdoc的内容是0,1,1,1,1,3。copyListOfNgramCounteachdoc的类型也是thrust::device_vector<int>。
编辑:
end.first = storeNcCounts.begin();
end.second = storeCompactedPositions.begin();
int indexToWriteForIndexesarr = 0;
for(int i =0 ; i < numDocs; i++){
iter = end.first;
end = thrust::unique_by_key_copy(copyListOfNgramCounteachdoc.begin() + (i*numUniqueNgrams), copyListOfNgramCounteachdoc.begin()+(i*numUniqueNgrams)+ numUniqueNgrams,positions.begin() + (i*numUniqueNgrams),end.first,end.second);
int numElementsCopied = (end.first - iter);
endIndex = beginIndex + numElementsCopied - 1;
storeBeginIndexEndIndexSCNCtoRead[indexToWriteForIndexesarr++] = beginIndex;
storeBeginIndexEndIndexSCNCtoRead[indexToWriteForIndexesarr++] = endIndex;
beginIndex = endIndex + 1;
}发布于 2012-06-18 13:21:24
我认为在这种情况下您想要使用的是thrust::unique_by_key_copy,但请继续阅读。
问题是unique_by_key不会更新您的输入数组,除非迫不得已。在第一个调用的情况下,它可以通过删除重复的1返回唯一键序列--通过将返回的迭代器向前移动,而不是实际压缩输入数组。
如果您用下面的循环替换您的循环,您可以看到发生了什么:
end.first = copyListOfNgramCounteachdoc.begin();
end.second = positions.begin();
thrust::device_vector<int>::iterator iter;
for(int i =0 ; i < numDocs; i++){
cout <<"before ";
for(iter = end.first; iter != end.first+3; iter++) cout<<*iter;
end = thrust::unique_by_key(end.first, end.first + 3,end.second);
cout <<" after ";
for(iter = copyListOfNgramCounteachdoc.begin(); iter != end.first; iter++) cout<<*iter;
cout << endl;
for(int i =0 ; i< 6; i++) cout<<copyListOfNgramCounteachdoc[i];
cout << endl;
}对于这段代码,我得到以下输出:
before 011 after 01
011223
before 122 after 0112
011223您可以看到copyListofNgramCounteachdoc中的值没有改变。这是有效的行为。如果您使用unique_by_key_copy而不是unique_by_key,那么为了保证唯一性,实际上将强制压缩这些值,但在这种情况下,因为每个序列中只有两个值,所以没有必要。医生说:
首先,返回值是一个迭代器new_last,使得范围[first,new_last]中的任何两个连续元素都不相等。范围[new_last,last]中的迭代器仍然是可解引用的,但它们所指向的元素是未指定的。unique是稳定的,这意味着未删除的元素的相对顺序是不变的。
如果你使用unique_by_key_copy,那么Thrust将被强制复制唯一的键和值(具有明显的成本影响),并且你应该看到你所期望的行为。
顺便说一句,如果您可以在对unique_by_key的单个调用中做到这一点,而不是在循环中完成它们,我建议您这样做。
https://stackoverflow.com/questions/11070109
复制相似问题