It depends on what you mean by "more effective." First, is it really a bottle neck? Of course, there are a lot of 100 thousand records, but if you only need this every few minutes, it is normal if the algorithm takes a couple of seconds.
The only area for improvement that I see is memory usage. If this is a concern, you can skip the multimap generation and just save the counter map, something like this (beware, my C ++ is a bit rusty):
std::map<int, int> countFrequency; // count => how many customers with that count for ( std::map<int, int>::const_iterator it = uc.begin(); it != uc.end(); ++it ) { // If it->second is not yet in countFrequency, // the default constructor initializes it to 0. countFrequency[it->second] += 1; } // Now write this out for ( std::map<int, int>::const_iterator it = countFrequency.begin(); it != countFrequency.end(); ++it ) { std::cout << "==> There are " << it->second << " users that have bought " << it->first << " products(s)" << std::endl; }
If a user is added and buys count
elements, you can update countFrequency
with
countFrequency[count] += 1;
If an existing user moves from oldCount
to newCount
, you can update countFrequency
with
countFrequency[oldCount] -= 1; countFrequency[newCount] += 1;
Now, as an aside, I recommend using unsigned int
for counting (if there is no legitimate reason for negative counting) and typedef'ing of type userID
for extra readability.
source share