我在这里遇到了一个非常烦人的问题。我在这个挑战中的目标是返回一个数组,其中包含按数量计算的 5 个最活跃买家的名称。stockSymbols 持有这些名称,而购买的总数已成功计算并放入 totalBought 数组。然后,我尝试找出前 5 个最大的并将他们的名字放入 totalSold 并返回。
我是 C++ 的绝对新手,所以我知道这种做事方式是不正确的。它也不会编译,它会在所有地方抛出内存错误(从 if(biggest[0] < totalBought[i]) 行开始或周围开始)。
如果你们中的任何人知道成功完成这项工作的更好方法,我将不胜感激您的意见,或者如果您知道如何使这种方式工作,那也将非常有用。不过,我真的很想找到最有效的方法(就速度而言)来计算它。
非常感谢。
string* Analyser::topFiveBuyers()
{
// Your code
string* totalSold;
totalSold = new string[5];
string stockSymbols[] = {"W Buffet", "P Lynch", "G Soros", "J Neff", "Hargreaves Lansdown",
"Sippdeal", "Saga", "Halifax", "iWeb", "Alliance Trust", "Clubfinance", "Lloyds TSB", "Saxo" };
int totalBought[13];
for(int i = 0; i < nTransactions; i++)
{
for(int j = 0; j < 13; j++)
{
if(transArray[i].buyerName == stockSymbols[j])
{
totalBought[j] += transArray[i].numShares;
}
}
}
int biggest[] = {-1, -1, -1, -1, -1};
for(int i = 0; i < 13; i++)
{
if(biggest[0] < totalBought[i])
{
biggest[4] = biggest[3];
biggest[3] = biggest[2];
biggest[2] = biggest[1];
biggest[1] = biggest[0];
biggest[0] = totalBought[i];
totalSold[0] = stockSymbols[i];
}
else if(biggest[1] < totalBought[i])
{
biggest[4] = biggest[3];
biggest[3] = biggest[2];
biggest[2] = biggest[1];
biggest[1] = totalBought[i];
totalSold[1] = stockSymbols[i];
}
else if(biggest[2] < totalBought[i])
{
biggest[4] = biggest[3];
biggest[3] = biggest[2];
biggest[2] = totalBought[i];
totalSold[2] = stockSymbols[i];
}
else if(biggest[3] < totalBought[i])
{
biggest[4] = biggest[3];
biggest[3] = totalBought[i];
totalSold[3] = stockSymbols[i];
}
else if(biggest[4] < totalBought[i])
{
biggest[4] = totalBought[i];
totalSold[4] = stockSymbols[i];
}
}
return totalSold;
}