使用向量排序

时间:2013-09-29 05:53:21

标签: c++

大家好,我正在写一个股票市场的程序,我从文件中读取并按符号和百分比收益/损失排序。我已完成符号排序,但无法确定增益损失百分比。基本上我被指示使用矢量。我们需要生成按增益/损失百分比排序的列表,我需要按此组件对库存清单进行排序。但是,我不是按组件百分比获得/损失对列表进行物理排序;而是提供关于该组件的逻辑排序。 所以基本上我添加了一个数据成员,一个向量来保存由组件百分比增益/损失排序的股票列表的索引。我把它称为数组indexByGain。因此,当我打印按百分比增益/损失排序的列表时,我使用数组indexByGain来打印列表。我的问题是我需要帮助如何开始,如果有人可以给我一个例子或解释如何去做这个我可以继续或纠正我的粗略草案将有所帮助。我有一个想法,但与我裸露,因为这是一个草稿。下面是我的代码的草稿。 stockType与从文件中存储数据的位置有关。

   #include <iostream>
   #include "stockType.h"

  class stockListType
   {
     public:
       void sortBySymbols();//sort out symbols and it comiples correctly.
       void sortByGain();
       void printByGain();
       void insert(const stockType& item);
     private:
   vector<int> indexByGain;//declared a vector array indexByGain..
    vector<stockType> list;
   };

     void stockListType::insert(const stockType& item)
    {
       list.push_back(item)//inserts the data from file to vector array.
     }
      //function prints out the gain
     void stockListType::printByGain()
 {
    //my code to print out the gain..
   }
     //function to sort the gain and this is where i am stuck.
      void stockListType::sortGain()
       {

          int i, j, min, maxindex;
          for(i=0;i<list.size();i++)
          {
             min = i;
             for(j=i+1;j<list.size();j++)
               list[maxindex].getPercentage()<list[j].getPercentage();
                 maxindex = j;
                 indexGain.push_back(maxindex);
           }

请粗略选择。我知道我错了,但我是在一个良好的基础上完成的。拜托,你可以帮助我或纠正我。谢谢。哦,对不起,我忘了getPercentage()计算并返回百分比增益/损失。

1 个答案:

答案 0 :(得分:2)

初始化索引并使用std :: sort:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    struct Data {
        int value;
        int percent;
    };
    typedef std::vector<Data> DataVector;
    typedef DataVector::size_type size_type;
    typedef std::vector<size_type> IndexVector;

    DataVector data { { 1, 1 }, { 2, -2 }, { 3, 3 }, { 4, -4 }, { 5, 5} };
    IndexVector index;
    index.resize(data.size());
    for(size_type i = 0; i < data.size(); ++i) {
        index[i] = i;
    }

    struct Less
    {
        const DataVector& data;
        Less(const DataVector& data)
        :   data(data)
        {}

        bool operator () (size_type a, size_type b) {
            return data[a].percent < data[b].percent;
        }
    };
    std::sort(index.begin(), index.end(), Less(data));
    for(size_type i = 0; i < index.size(); ++i) {
        std::cout << data[index[i]].value << ": " << data[index[i]].percent << std::endl;
    }
}

您可以使用C ++ 11:

std::sort(index.begin(), index.end(),
        [&](size_type a, size_type b) { return data[a].percent < data[b].percent; }
    );
for(auto i: index)
    std::cout << data[i].value << ": " << data[i].percent << std::endl;