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() がパーセントの利益/損失を計算して返すことを忘れる前に申し訳ありません。

4

1 に答える 1

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;
于 2013-09-29T06:28:09.177 に答える