爲了怎麼算經常在號碼列表中出現的每個號碼,您可以執行以下操作:
#include <iostream>
#include <vector>
#include <map>
#include <cstdlib>
我們需要這些頭輸出,存儲的號碼,存儲計,和rand()來生成示例。
std::vector<int> generate_numbers(int amount, int max_num)
{
std::vector<int> numbers(amount);
for (int i = 0; i < amount; ++i) {
numbers[i] = rand() % max_num + 1;
}
return numbers;
}
生成一串隨機數的幫助方法。
std::map<int, int> count_numbers(const std::vector<int> &numbers)
{
// Count numbers
std::map<int, int> counts; // We will store the count in a map for fast lookup (C++11's unordered_map has even faster lookup)
for (size_t i = 0; i < numbers.size(); ++i) { // For each number
counts[numbers[i]]++; // Add 1 to its count
}
return counts;
}
上面的方法計算,這是你的問題的本質。對於我們遇到的每個數字,我們增加它的計數。
void print_counts(const std::map<int, int> &counts)
{
for(std::map<int, int>::const_iterator it = counts.begin();
it != counts.end(); ++it) { // For each number stored in the map (this automatically filters those with count 0)
std::cout << it->first << ": " << it->second << std::endl; // Output its count
}
}
最後,顯示我們的結果的方法。由於我們從未對任何出現零次的數字採取行動,因此它們不在地圖中,並且將從輸出中省略。
int main() {
srand(0); // So that we get the same result every time
std::vector<int> numbers = generate_numbers(10000, 500);
std::map<int, int> counts = count_numbers(numbers);
return 0;
}
把它放在一起。 See this code run。
你需要什麼幫助?到目前爲止您嘗試過哪些具體的問題? – BoBTFish
我們不應該爲你編寫程序。告訴我們你已經嘗試過了。如果您遇到任何問題,我們很樂意爲您提供幫助。 –
看看[std :: map](http://en.cppreference.com/w/cpp/container/map)。或者如果你使用C++ 11,[std :: unordered_map](http://en.cppreference.com/w/cpp/container/unordered_map)。如果您有任何代碼示例,請將其編輯到您的問題中,因爲您無法在註釋中格式化代碼。 –