Subj : Re: any function to handle this kind of counting? To : comp.programming From : Gerry Quinn Date : Sat Jul 30 2005 03:37 pm In article , a@cuhk.edu.hk says... > Dear all, > > i have generated a 2000 X 1 vector, e.g. > and then i want to count, say, for "1", there are two A's, one E, ... > > it seems that a for loop can do the job but as we don't know how many > instances there are, i.e. don't know A, C, E and then what will occur in > this corresponding vector, is there any function which is devoted to handle > this kind of counting problem? thx!! Well, I guess there are libraries for linked lists, vectors etc. There are also sorting functions that can often make such problems easier. The following is untested C++ to count them directly. I will treat both vectors as containing ints though I'll call them 'nums' and 'lets'. It's trivial to convert the second to and from chars if required (e.g. just use val = letter - 'A'.) Besides, they could be enums for all I know. The algorithm should be modified if speed is at a premium and there are a large number of different letter values. 'targ' is the required number, 1 in the example. One could modify it easily to return a complete solution for all numbers as a vector of vectors, using a similar methodology. If the data are in fact C-style arrays rather than vectors, it's just as easy to implement, but using an STL vector for the result makes the solution very easy in C++: #include using namespace std; class Datum { public: int letter; int count; }; vector< Datum > result; ASSERT( nums.size() == lets.size() ); for ( int iLet = 0; iLet < lets.size(); iLet++ ) { if ( nums[ iLet ] != targ ) { continue; } int iRes = 0; while ( iRes < result.size() ) { if ( result[ iRes ].letter == lets[ iLet ] ) { break; } iRes++; } if ( iRes == result.size() ) { Datum datum; datum.letter = lets[ iLet ]; datum.count = 0; result.push_back( datum ); } result[ iRes ].count++; } - Gerry Quinn .