如何解决指针的字母顺序化排序向量
| 我有一个指向一组Critic对象的指针向量。每个评论家都具有诸如UserID,First Name,Last Name等属性。 我模拟了修改后的quickSort,以便按每个评论家的名字对指针向量进行排序。该函数按预期工作,但仅适用于向量中的前几个实例。void quickSortCritics(vector<Critic*> & v,int from,int to)
{
if (from < to)
{
int middle = partition(v,from,to);
quickSortCritics(v,middle - 1);
quickSortCritics(v,middle + 1,from);
}
}
int partition(vector<Critic*> & v,int to)
{
char pivot = (v[from]->getFirstName())[0];
int left_index = from - 1;
int right_index = to + 1;
do
{
do
{
right_index--;
} while ( (v[right_index]->getFirstName())[0] > pivot);
do
{
left_index++;
} while ( (v[left_index]->getFirstName())[0] < pivot);
if (left_index < right_index)
{
cout << \"swapping \" << v[left_index]->getFirstName() << \" with \" << v[right_index]->getFirstName() << endl;
swap(v[left_index],v[right_index]);
}
} while ( left_index < right_index );
return right_index;
}
有什么建议么?
解决方法
如果不是家庭作业,那么为什么不使用提供比较器的ѭ1作为第三个参数呢?
bool compare_func(const Critic* c1,const Critic* c2) { /***implement it***/ }
vector<Critic*> v;
//...
std::sort(v.begin(),v.end(),compare_func);
,如果您仍想使用自己的快速排序,则将是这样。我假设您正在使用std :: string。
void quickSortCritics(vector<Critic*>& v,int top,int bottom){
if(top < bottom){
int middle = partition(v,top,bottom);
quickSortCritics(v,middle); // sort top partition
quickSortCritics(v,middle + 1,bottom); //sort bottom partition
}
}
int partition(vector<Critic*>& v,int bottom){
std::string pivot = v[top]->getFirstName();
int left_index = top - 1;
int right_index = bottom + 1;
string tmp;
do{
do{
right_index--;
}while( pivot.compare(v[right_index]->getFirstName()) < 0 );
do{
left_index++;
}while( pivot.compare(v[left_index]->getFirstName()) > 0);
if (left_index < right_index)
swap(v[left_index],v[right_index]);
}while( left_index < right_index );
return right_index;
}
然后,您将这样称呼它:
quickSortCritics(your_vector,0,
your_vector.size()-1);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。