I have a vector<purchases> v where purchases is defined as:

struct purchases
{
  string name;
  int amount;
  string item;
};

vector<purchases> v;

I need to find the 3 top buyers.
ie. the name of the top 3 people with the highest accumulated amount.

The problem I have is when I sort the values the same buyer can appear in the top 3 more than once.

I need to combine way to combine all of the amounts from the same buyer before comparing them. Any ideas on how to do this??

To clarify, you want to identify the top three buyers, where each buyer could have bought any amount of any item? That is, if a buyer bought three of item A and two of item B, that buyer has bought five overall?

Sounds like you need to examine each element in turn, and for each buyer, keep track of how much that buyer has bought, and then sort THAT record for the top buyers.

How would you do it on paper? You might do something like:

Look at first element.
Write the buyer's name down with the number of items bought.
Look at next element.
Compare buyer's name of the next element with existing list of buyers.
If buyer's name already written down, add to their existing number of items bought.
If buyer's name NOT already written down, write the buyer's name down with the number of items bought.
Repeat for all elements.

This is very easily turned into code. This is programming; thinking about problems in a way that lends itself to a programmatic solution. The rest is memorising syntax.

Then sort your list by amount, either as you add each one or later after it's complete.

I understand the logic of your solution but I'm having problems converting it to code. This is what I have got so far. (m is the vector which contains the original set of transactions.)

vector <purchases> c; //hold buyers name with their accumulated amount of purchases

    c[0]=m[0]; // set c to equal m for the first element

         for(int i=0; i<m.size(); ++i) 
         {
             for(int j=0; j<c.size(); ++j)
             {
        if(m[i].name==c[j].name) //check if names are the same 
        c[j].numShares= c[j].amount + m[i].amount; //add to their existing number of items bought.

        else
            c.push_back(m[i]); //add purchase details to c
             }
         }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.