我试图找到迭代器的索引/位置,我使用thrust :: distance()。但是,它会返回奇怪的值。 向量大小为10.当我使用此方法时,它返回值“131”。 这是一个完全有效的例子。
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/random.h>
#include <thrust/unique.h>
#include <thrust/reduce.h>
#include <thrust/iterator/constant_iterator.h>
using namespace std;
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, ""));
std::cout << std::endl;
}
int main()
{
thrust::device_vector<int> x;
x.push_back(1);
x.push_back(10);
x.push_back(1);
x.push_back(11);
x.push_back(1);
x.push_back(11);
thrust::device_vector<int> y(10);
print_vector("Original",x);
thrust::sort(x.begin(),x.end());
print_vector("sort",x);
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
std::cout<<*it<<std::endl;
//int newsize=it-y.begin();
int newsize=thrust::distance(y.begin(),it);
cout<<"nsz:"<<newsize<<endl;
return 0;
}
答案 0 :(得分:1)
迭代器it
是根据向量x
:
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
^ ^
但是你要求从迭代器到向量y
的开头的距离:
int newsize=thrust::distance(y.begin(),it);
^
这没有意义。 it
与向量y
之间没有明确的关系。
如果你要求距离向量x
的开头,你会得到更明智的结果:
$ cat t1244.cu
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/random.h>
#include <thrust/unique.h>
#include <thrust/reduce.h>
#include <thrust/iterator/constant_iterator.h>
using namespace std;
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
int main()
{
thrust::device_vector<int> x;
x.push_back(1);
x.push_back(10);
x.push_back(1);
x.push_back(11);
x.push_back(1);
x.push_back(11);
thrust::device_vector<int> y(10);
print_vector("Original",x);
thrust::sort(x.begin(),x.end());
print_vector("sort",x);
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
std::cout<<*it<<std::endl;
//int newsize=it-y.begin();
int newsize=thrust::distance(x.begin(),it);
cout<<"nsz:"<<newsize<<endl;
return 0;
}
$ nvcc -o t1244 t1244.cu
$ ./t1244
Original 1 10 1 11 1 11
sort 1 1 1 10 11 11
10
nsz:3
$