Alphabetizing(排序)指针矢量

Chr*_*asa 1 c++ sorting pointers vector quicksort

我有一个指针向量,指向一组Critic对象.每个评论家都有UserID,名字,姓氏等属性.

我模拟了一个修改过的quickSort,以便按每个评论家的名字对指针向量进行排序.该函数按预期工作,但仅适用于向量中的前几个实例.

void quickSortCritics(vector<Critic*> & v, int from, int to)
{
  if (from < to) 
  {
    int middle = partition(v, from, to);
    quickSortCritics(v, from, middle - 1);
    quickSortCritics(v, middle + 1, from);
  }
}

int partition(vector<Critic*> & v, int from, 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;
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Naw*_*waz 7

如果它不是作业,那你为什么不使用std::sort比较器作为第三个参数?

bool compare_func(const Critic* c1,const Critic* c2) { /***implement it***/ }

vector<Critic*> v;
//...

std::sort(v.begin(), v.end(), compare_func);
Run Code Online (Sandbox Code Playgroud)