[英]Counter in arrays c++
我那里有一個非常簡單的代碼,可以計算數組中需要多少值。
for (int i = 0; i < dm; i++)
{
if (arr[i] == c)
{
counter++;
}
};
但是我需要使它有些棘手。我需要計算相同值的數量。 想象一下,我有一個數組{4,4,4,3,3,2,2,1,1,0,0,0},我需要在那里找到多少個“孿生子”。 所以3,2,1是雙胞胎,因為他們只有1個確切的朋友。 我嘗試了2個fors和2個計數器,但是仍然遇到麻煩。 謝謝。 希望你理解我所說的“雙胞胎”。 x和x是雙胞胎,而y,y,y不是(以防萬一)
我將創建一個映射,該映射對數組中的每個數字都進行計數。 該代碼如下所示:
#include <iostream>
#include <map>
int main()
{
const int numberOfElements = 12;
int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
std::map<int,int> counts;
for (int i=0; i < numberOfElements; i++) {
counts[array[i]]++;
}
for (auto x : counts) {
if (x.second == 2) {
cout << "pair: " << x.first << endl;
}
}
return 0;
}
如果-由於某種原因-元素的范圍受到限制,則還可以使用“純”數組來計算出現次數。 例如,如果元素在0..4
的范圍內,則可以使用以下片段:
const int numberOfElements = 12;
const int elementMax = 4;
int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int counts[elementMax+1] = {};
for (int i=0; i<numberOfElements; i++) {
counts[array[i]]++;
}
for (int i=0; i <= elementMax; i++) {
if (counts[i] == 2) {
cout << "pair: " << i << endl;
}
}
而且,如果對數組進行了排序,那么沒有計數器數組的解決方案將如下所示:
const int numberOfElements = 12;
int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int prev = -1;
int count = 0;
for (int i=0; i<numberOfElements; i++) {
if (array[i] == prev) {
count++;
}
else {
if (count == 2) {
cout << "pair: " << prev << endl;
}
count=1;
prev = array[i];
}
}
if (prev >= 0 && count==2) {
cout << "pair: " << prev << endl;
}
您可以一次性完成該任務,並使用二進制搜索來提高效率:
int arr[] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int twins = 0;
for( auto i = std::begin( arr ); i != std::end( arr ); ) {
auto next = std::upper_bound( i, std::end( arr ), *i, std::greater<int>() );
if( std::distance( i, next ) == 2 ) ++twins;
i = next;
}
如果數組std::upper_bound
中沒有太多重復項,可能效率不高並且可以輕松替換:
auto next = std::find_if( std::next( i ), std::end( arr ), [i]( int n ) { return *i != n; } );
不使用其他數組的解決方案:
int twins_counter = 0;
for (int i = 0; i < dm; i++)
{
int counter = 0; // counter for elements
for (int j = 0; j < dm; j++)
{
if (arr[i] == arr[j])
{
if( j < i )
{
break; // we have searched twin for this element already
}
counter++;
if( counter > 2 )
{
break; // we meet element third time, it isn't twin
}
}
}
if( counter == 2 )
{
twins_counter++;
}
};
對於排序(向上或向下)的數組,一個周期就足夠了:
int twins_counter = 0;
int counter = 1;
for (int i = 1; i < dm; i++)
{
if( arr[i] == arr[i-1] )
{
counter++;
}
else
{
if( counter == 2 )
{
twins_counter++;
counter = 1;
}
}
}
// check last value
if( counter == 2 )
{
twins_counter++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.