最常见的5个数组c++

Top 5 most frequent from an array c++

本文关键字:数组 c++ 5个 常见      更新时间:2023-10-16

嗨,我有一个数组,我想从这个数组中得到最频繁出现的前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个出现的元素?

如果需要更多的信息,我很乐意提供。

提前感谢Andrew

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

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


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

可以是这样的:

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;
}

另外,当您执行事务时,请记住增加映射中事务的计数器。

注意:此解决方案未经过测试,只是在浏览器中编写。

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

累计股票代码:

  • 计数到map<string, int>
  • 最高的5个符号变成set<string>
  • 将最高5个符号的最低频率转换为int
  • 将最高的5个符号中的最低的变为string