get_number()返回一个整数.我将调用它30次并计算返回的不同整数的数量.我的计划是将这些数字放入std::array<int,30>,然后对其进行排序std::unique.
这是一个好的解决方案吗?还有更好的吗?这段代码将成为我程序的瓶颈.
我认为应该有一个基于散列的解决方案,但是当我只有30个元素时,它的开销可能太大了?
编辑我改变了唯一的不同.例:
{1,1,1,1} => 1
{1,2,3,4} => 4
{1,3,3,1} => 2
Run Code Online (Sandbox Code Playgroud)
我会用std::set<int>它,因为它更简单:
std::set<int> s;
for(/*loop 30 times*/)
{
s.insert(get_number());
}
std::cout << s.size() << std::endl; // You get count of unique numbers
Run Code Online (Sandbox Code Playgroud)
如果你想计算每个唯一号码的返回时间,我建议 map
std::map<int, int> s;
for(int i=0; i<30; i++)
{
s[get_number()]++;
}
cout << s.size() << std::endl; // total count of distinct numbers returned
for (auto it : s)
{
cout << it.first << " " << it.second<< std::endl; // each number and return counts
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
274 次 |
| 最近记录: |