【问题标题】:Having trouble with my sorting function我的排序功能有问题
【发布时间】:2016-10-27 08:04:18
【问题描述】:

首先,让我展示一下我的代码。

void findRev(Items* products[], int numOfProd) {

    for (int i = 0; i < (numOfProd - 1); i++) {
        double rev1 = products[i]->price * products[i]->numSold;
        double rev2 = products[i + 1]->price * products[i + 1]->numSold;

        if (rev1 > rev2) {
            Items* temp = products[i];
            Items* temp2 = products[i + 1];
            temp2 = products[i];
            temp = products[i + 1];
        }
    }
}

我有一个struct 的不同项目。我正在尝试按收入对它们进行排序,但我必须先找到收入。

我知道我可以在我的结构中添加一个收入字段,但我的教授说我们不允许这样做。

我编写了这个函数,但它并没有按照我想要的方式工作。我以前使用过冒泡排序和选择排序。我似乎无法弄清楚如何在这种情况下使用其中一个。我翻遍了我的书和网上。我的教授最好在排序循环中找到收入。我只是不知道怎么做。反正我可以让它工作吗?

【问题讨论】:

  • 您必须编写自己的排序函数还是可以使用标准算法?如果没有,您可以搜索一下冒泡排序。

标签: arrays visual-studio sorting c++11 struct


【解决方案1】:

您可以先使用数组来存储收入,然后根据该数组对产品进行排序,如下所示:

void findRev(Items* products[], int numOfProd) {
    double* rev= new double[numOfProd];
    for (int i = 0; i < numOfProd; i++)
        rev[i] = products[i]->price * products[i]->numSold;

    // bubble sort
    Items *tempItem;
    double tempDouble;
    for(int i=0; i< numOfProd; i++)
      for(int j=0; j< numOfProd - i -1; j++)
         if(rev[j] > rev[j+1]){
           tempDouble = rev[j];
           rev[j] = rev[j+1];
           rev[j+1] = tempDouble;
           tempItem = products[j];
           products[j] = products[j+1];
           products[j+1] = tempItem;
          }

      delete[] rev;
 }

【讨论】:

  • 这很好用,但 numOfProd 不是常数,所以我无法将数组 rev 设置为该大小。
  • 是的,对此我很抱歉,只需将其设为动态数组即可:double* rev= new double[numOfProd];
  • 你应该在完成后删除数组,否则你会泄漏内存。
  • 谢谢,我在这里读到了这个stackoverflow.com/questions/28833300/…
【解决方案2】:

正确的排序方式是使用std::sort

通过投影排序时使用std::sort的正确方法是通过投影进行排序。

template<class F>
struct sort_by_t {
  F f;
  template<class Lhs, class Rhs>
  bool operator()(Lhs const& lhs, Rhs const& rhs) const {
    return f(lhs) < f(rhs);
  }
};
template<class F>
sort_by_t<typename std::decay<F>::type>
sort_by( F&& f ) { return {std::forward<F>(f)}; }

void findRef( Items const*const* products, int numOfProd) {
  std::sort( products, products+numOfProd,
    sortby([](Items const* i) { return i->price * i->numSold; })
  );
}

你的代码甚至都没有排序,更别说合理了。

上面的代码高效简洁地对数组进行排序。 sort_by 代码是样板文件,可以在其他地方重复使用。

这是后 C++11 中的 sort_t-less sort_by

template<class F>
auto sort_by(F&& f) {
  return [f=std::forward<F>(f)](auto&& lhs, auto&& rhs){
    return f(lhs)<f(rhs);
  };
}

【讨论】:

    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    相关资源
    最近更新 更多