Can you guarantee that the array is always sorted as per your example? Or, can you guarantee that all occurences of a given element will be consecutive? If so, simpler, faster algorithms with O(1) extra storage exist.
–
Eamon NerbonneSep 26 '10 at 15:25

5 Answers
5

Since you are including vector anway, why not replace int *b=new int [n]; with std::vector<int> b(n)? This also takes care of releasing the memory, you forgot to delete[] b.

But as others have mentioned, your solution will break if the array contains elements larger than n. A better approach might be to count the elements with a mapping to int. That way, you can also count elements that cannot be used as an array index, for example strings.

There is also no reason to limit ourselves to arrays. Here is a generic solution that works with any container of any less-than comparable element type:

Uhm, your edit is probably technically fine, but given the question, I think your proposed code is overcomplicated. The questioner is still learning the basics, let's not overwhelm him with templates and iterator details just yet...
–
Eamon NerbonneSep 26 '10 at 15:35

@FredOverflow the typename applies to value_type, not to map_t. If you omit the typename, then map_t::value_type is taken as a non-type and then the compiler is granted to reject by_second<map_t::value_type> at the time parsing the template because by_second requires a type argument.
–
Johannes Schaub - litbSep 26 '10 at 16:15

1

@Eamon: A task like this (well, it was counting word occurrences in a text) was among the first few my students ever had to do. Of course, by that time they could only use templates, but that was fine. Manually fiddling with memory is far worse than this.
–
sbiSep 26 '10 at 19:22

Your way of doing (b[a[i]]||0)+1 works in languages like Javascipt, Perl where an un-initialized array element will have a special value called undef or null. C++ does not have anything like that and an uninitilzed array will have garbage.