使用向量对收益/损失百分比进行排序
sorting percent gain/loss using vectors
大家好,我正在编写一个股票市场的程序,我从文件中读取并用符号和百分比收益/损失进行排序。我已经完成了符号排序,但在确定百分比增益损失时遇到问题。基本上我被指示使用向量。我们需要生成按百分比收益/损失排序的列表,我需要按此组件对股票列表进行排序。但是,我不会按组件百分比收益/损失对列表进行物理排序;而是提供与此组件相关的逻辑顺序。所以基本上我添加了一个数据成员,一个向量来保存按组件收益/损失百分比排序的股票列表的指数。我称之为数组索引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());
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 使用向量对收益/损失百分比进行排序