使用向量对收益/损失百分比进行排序

sorting percent gain/loss using vectors

本文关键字:百分比 排序 损失 向量 收益      更新时间:2023-10-16

大家好,我正在编写一个股票市场的程序,我从文件中读取并用符号和百分比收益/损失进行排序。我已经完成了符号排序,但在确定百分比增益损失时遇到问题。基本上我被指示使用向量。我们需要生成按百分比收益/损失排序的列表,我需要按此组件对股票列表进行排序。但是,我不会按组件百分比收益/损失对列表进行物理排序;而是提供与此组件相关的逻辑顺序。所以基本上我添加了一个数据成员,一个向量来保存按组件收益/损失百分比排序的股票列表的指数。我称之为数组索引ByGain。因此,当我打印按百分比增益/损失排序的列表时,我使用数组 indexByGain 来打印列表。我的问题是我需要有关如何开始的帮助,如果有人可以帮助我解释如何去做或解释他们使用数组所做的示例代码将有很大帮助。下面是对收益/损失百分比进行排序的示例代码:

/* Name: stock_sort() */
 /* Purpose: Sort stocks (stockListType) by percent gained or loss, ascending order */
 /* Parameters: None */
/* Preconditions: list of stocks should be created and initialized as well as       
    sortIndicesGainLoss array */
 /* Postconditions: sortIndicesGainLoss holds the indices of stockList sorted 
    by  gain/loss */
    void stockListType::stock_sort() {
      int i, j;
       int min;
       int temp1, temp2;

        for(i = 0; i < length; i++)
         sortIndicesGainLoss[i] = i;
          for(i = 0; i < length; i++)
          {
               min = i;
               for(j = i + 1; j < length; ++j)
         if(list[sortIndicesGainLoss[min]].percent_gain()>list[sortIndicesGainLoss[j]].percent_gain())
                       min = j;
                   temp1 = sortIndicesGainLoss[i];
                 sortIndicesGainLoss[i] = sortIndicesGainLoss[min];
                     sortIndicesGainLoss[min] = temp1;
                }
                     }

你如何使用向量来解决这个问题。 我真的很难尝试使用矢量来整理股票,因为我对如何去做感到困惑。如果有人可以帮助我,我将不胜感激。谢谢

您不需要自己实现选择排序。您可以使用std::sort()

#include <algorithm>
typedef int PERCENTGAINLOSS;
struct STOCK
{
    PERCENTGAINLOSS PercentGainLoss;
    // ...
};
bool operator < (STOCK& a, STOCK& b) {return (a.PercentGainLoss < b.PercentGainLoss);}
// ...
std::vector<STOCK> vector_var;
// Add elements to vector_var
std::sort(vector_var.begin(), vector_var.end());