2013-09-29 60 views
0

大家好我正在写一个股票市场的程序,我从一个文件中读取数据并按照符号和百分比获得/损失进行排序。我已完成符号分类,但无法确定收益损失百分比。基本上我被指示使用矢量。我们被要求产生按百分比收益/损失排序的清单,我需要按这个组件排序清单。不过,我不是要按组件百分比收益/损失对物品进行实物分类;而是提供关于该组件的逻辑顺序。 所以基本上我增加了一个数据成员,一个矢量来保存由组件百分比收益/损失订购的股票列表的指数。我把它称为数组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()计算并返回百分比收益/损失。

回答

2

初始化索引和使用std ::排序:

#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; 
+0

要知道,的std ::排序调用基的拷贝构造函数元素几次。如果性能下降,请检查您的拷贝构造函数。 – cup

+0

@cup什么是基本元素? –