0

嗨,我有一个数组,我希望从这个数组中获得最常出现的前 5 个。

static std::string pickRandomStockSymbol()
{
    static std::string stockSymbols[] = {"SIRI", "INTC", "ZNGA", "BBRY", "MSFT", 
        "QQQ", "CSCO", "FB", "MU", "DELL", "AMAT", "NWSA", "AAPL", "AFFY", "ORCL", 
        "YHOO", "GRPN", "MDLZ", "VOD", "CMCSA" };

    return stockSymbols[rand() % 20];

^^ 这是我将使用的数组。

交易是使用这个结构随机创建的:

struct Transaction
{
string stockSymbol;     // String containing the stock symbol, e.g. "AAPL"
string buyerName;       // String containing the buyer's name e.g. "Mr Brown"
int buyerAccount;       // Integer containing an eight digit account code
int numShares;          // Integer containing the number of sold shares
int pricePerShare;      // Integer containing the buy price per share
};

我打算在这个函数中这样做,我只是不知道我用什么方法来处理这个:

string* Analyser::topFiveStocks()
{

return new string[5];
}

有没有人愿意告诉我如何通过交易来获得这些前 5 个出现的元素?

如果需要更多信息,我将非常乐意提供。

在此先感谢,安德鲁

4

3 回答 3

2

您可以使用std::unordered_map带有股票代码的 a 作为键,并将交易计数作为值。然后将最高的五个放在 a 中std::vector并返回。

至于将前 N 个放入向量中,可以保持排序,并在每次插入后重新排序,以便事务数最高的股票排在第一位。然后很容易看出当前股票在遍历 map 时是否比向量中的最后一项(也就是向量中事务计数最小的项)具有更高的事务计数,然后将其添加到向量中并重新解决。


您也可以将地图中的所有股票添加到向量中,然后使用地图中的值对其进行排序,并获取向量中的前五个条目。

这可能是这样的:

using transaction_map_type = std::unordered_map<std::string, unsigned int>;

transaction_map_type transactions;

// ...

std::vector<std::string> topFiveStocks()
{

    std::vector<transaction_map_type::value_type> all_trans;

    // Copy all transaction into our vector
    std::copy(std::begin(transactions), std::end(transactions),
              std::back_inserter(all_trans));

    // Now sort the transactions
    std::sort(std::begin(all_trans), std::end(all_trans),
              [](const transaction_map_type::value_type& t1,
                 const transaction_map_type::value_type& t2)
              { return t1.second > t2.second; });

    // And get the top five (or less) results into a separate vector
    std::vector<std::string> top_five;

    auto count = std::min(5UL, all_trans.size());
    for (unsigned i = 0; i < count; i++)
        top_five.push_back(all_trans[i].first);

    return top_five;
}

另外,请记住在进行交易时增加地图中交易的计数器。

注意:此方案未经测试,只是在浏览器中编写。甚至可能无法编译。

于 2013-03-19T13:14:30.360 回答
0

累积股票代码:

  • 计入一个map<string, int>
  • 最高的 5 个符号set<string>
  • 最高 5 个符号的最低频率成int
  • 最高 5 个符号中最低的一个string
于 2013-03-19T13:25:37.043 回答
0

只需对数组进行排序,然后对其进行循环以计算相等的元素的最长间隔。

于 2013-03-19T13:13:40.637 回答