[英]C++ Instances of value in array? (Histogram)
我想知道在C ++中是否有可能解析數組並檢索整數出現在數組中的次數。 我正在嘗試對值進行直方圖繪制,但目前仍無法繼續。
如果這很重要,則它是一維數組,我正在使用此函數來打印數組:
void print(int a[], int n)
{
int j = 1;
cout << endl;
for(int i=0; i < n; i++)
{
if(!(j%6))
{
j=1; cout << endl << endl;
}
cout << right << setw(2) << a[i] << " ";
++j;
}
}
在此屏幕截圖中,這給了我正確的輸出:
http://i.imgur.com/P8Jzj1V.png
但是,一旦我轉到直方圖函數(我知道編碼錯誤),我將得到以下輸出:
http://i.imgur.com/WJtBjoF.png
因為在我當前的代碼中,它基於從數組中獲取的值打印星號:
for (int i = 0; i < size; i++)
{
cout << a[i] << ":" << bar(a[i-1]);
cout << endl;
}
PS-“ bar”函數僅根據指定的數字返回指定數量的'*'字符串。
我知道最后一點是不正確的,但這就是我要解決的問題。
有兩種簡單的方法:
std::unordered_map<int,int>
大小為2 ** sizeof(int)*CHAR_BIT
的數組過大。
讓我們來看看。 您可以將每個元素的計數保存在地圖中,將每個元素作為地圖的關鍵:
for (int i = 0; i < size; i++)
{
int current = a[i];
//if it doesn't find it it returns
if (countMap.find(current) != countMap.end())end()
{
countMap[current]++;
} else
{
countMap[current] = 1;
}
}
我不知道語法是否完全正確,但是類似這樣的方法可以滿足您的需求。
弄清楚了。
int tempVal = 0;
int tempTwo = 0;
int counter = 0;
for (int i = 0; i < size; i++) // Checks for histogram output
{
tempVal = a[i];
for (int j = 0; j < size; j++)
{
if(a[j] == tempVal)
{
counter += 1;
}
}
if(tempVal != tempTwo)
cout << setw(3) << tempVal << " : " << bar(counter) << endl;
tempTwo = tempVal;
counter = 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.