【问题标题】:Alphabetizing (Sorting) Vector of Pointers按字母顺序排列(排序)指针向量
【发布时间】:2011-09-02 03:22:48
【问题描述】:

我有一个指向一组 Critic 对象的指针向量。每个 Critic 都有 UserID、First Name、Last Name 等属性。

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

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;
}

有什么建议吗?

【问题讨论】:

  • 是的。不要自己实现排序。使用现有的实现。 STL 有 sort()。你可以在网上找到无数的快速排序实现。
  • 我的建议是使用带有自定义比较功能的std::sort。您不能这样做有什么特别的原因吗?

标签: c++ sorting pointers vector quicksort


【解决方案1】:

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

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

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

std::sort(v.begin(), v.end(), compare_func);

【讨论】:

    【解决方案2】:

    如果您仍想使用自己的快速排序,这就是它的样子。我假设您使用的是 std::string。

    void quickSortCritics(vector<Critic*>& v, int top, int bottom){
    
      if(top < bottom){
        int middle = partition(v, top, bottom);
        quickSortCritics(v, top, middle);  // sort top partition
        quickSortCritics(v, middle + 1, bottom);  //sort bottom partition
      }
    }
    
    int partition(vector<Critic*>& v, int top, 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);

    【讨论】:

    • pivot.compare(v[right_index]-&gt;getFirstName()) &lt; 0可以写成pivot &lt; v[right_index]-&gt;getFirstName()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2015-12-09
    • 2018-09-15
    • 2023-03-28
    相关资源
    最近更新 更多