最常见的5个数组c++
Top 5 most frequent from an array c++
嗨,我有一个数组,我想从这个数组中得到最频繁出现的前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
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '