Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I want to count how many times a value appears in a 2-D array.

Status
Not open for further replies.

kouv

Programmer
Nov 25, 2003
1
GB
Hi all,

I have a 2-D array which stores the shade of each pixel of an image. The array is 256 by 256 and i want to count how many times each shade appears and store that in an one dimensional array.

Can anyone help me?

Cheers

</giannis>
 
What's a shade? Suppose a shade is 4-byte word (True Color pixel). Then we can implement binary tree with counters in leaves, or (slightly simpler) use STL map container.
Code sceleton for map<> approach:
Code:
#include <iostream>
#include <map>
using namespace std;

typedef map<unsigned,int> Map;
typedef pair<unsigned,int> Pair;

int CountColors(unsigned img[256][256])
{
  Map count;
  for (int i = 0; i < 256; ++i)
  for (int j = 0; j < 256; ++j)
    ++count[img]i[/img][j]]; // new pair created and init with 0
  Map::const_iterator x;
  Pair p;
  for (x = count.begin();x != count.end();++x)
  {
    p = *x;
    cout << hex << p.first << &quot;\t&quot; << dec << p.second << endl;
  }
  return count.size();
}
No need to pass 2D array in the CountColors(). You may declare its parameter as unsigned[] and pass img size (number of pixels) as 2nd arg. You may also don't print results in the body but collect pixels and its counters in output array arg(s).
It's a very fast alg: STL map<> implementation uses trees.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top