我想排序concurrent_vector类型,其中hits_object
是:如何排序的矢量指针到结构
struct hits_object{
unsigned long int hash;
int position;
};
这里是我使用的代码:
concurrent_vector<hits_object*> hits;
for(i=0;...){
hits_object *obj=(hits_object*)malloc(sizeof(hits_object));
obj->position=i;
obj->hash=_prevHash[tid];
hits[i]=obj;
}
现在我填写了一个concurrent_vector<hits_object*>
,名为hits
。
但我想排序此位置属性上的concurrent_vector!
这里是里面有什么典型的命中对象的例子:
0 1106579628979812621
4237 1978650773053442200
512 3993899825106178560
4749 739461489314544830
1024 1629056397321528633
5261 593672691728388007
1536 5320457688954994196
5773 9017584181485751685
2048 4321435111178287982
6285 7119721556722067586
2560 7464213275487369093
6797 5363778283295017380
3072 255404511111217936
7309 5944699400741478979
3584 1069999863423687408
7821 3050974832468442286
4096 5230358938835592022
8333 5235649807131532071
我希望基于第一列(int
类型的“位置”)进行排序这一点。第二列是unsigned long int
类型的“散列”。
现在我已经尽力做到以下几点:
std::sort(hits.begin(),hits.end(),compareByPosition);
其中compareByPosition
被定义为:
int compareByPosition(const void *elem1,const void *elem2)
{
return ((hits_object*)elem1)->position > ((hits_object*)elem2)->position? 1 : -1;
}
,但我不断收到分段错误,当我把在该行std::sort(hits.begin(),hits.end(),compareByPosition);
请帮忙!
HTTP ://stackoverflow.com/questions/328955/how-to-use-带结构和比较功能的矢量结构 –
1 /你确定你确实需要存储指针吗?根据你给我们的代码,我会说存储值可能会更容易,更不容易出错。如果你真的想存储指针,你可以看看[Boost Pointer Container Library](http://www.boost.org/doc/libs/release/libs/ptr_container/doc/ptr_container)。html),或['boost :: indirect_iterator'](http://www.boost.org/doc/libs/release/libs/iterator/doc/indirect_iterator.html)。 2 /你不应该使用'malloc'来创建你的实例,而是使用'new'来代替:'malloc'不会构造这个对象,只是分配... –
...有些内存。 3 /要在你的容器中添加元素,你应该使用'push_back'或类似的方法,除非容器已经被填充了。 '[]'操作符用于访问已经在容器中的元素,而不是添加新元素。你提供的代码在内存中的某些点上写入数据时并未保留(假设'concurrent_vector'与'std :: vector'类似)。 –