Akansha Bagale
Akansha Bagale

Reputation: 149

Finding in a set of struct in c++

struct data
{
    int price;
    int qty;

    bool operator<(const data&rhs)const
    {
        return price<rhs.price;
    }
    bool operator==(const data&rhs)const
    {
        return price==rhs.price;
     }
};

set<data> bar;

int main(int argc,char** argv)
{
    data info;
    set<data>::iterator iter;
    int a[10]={100,120,500,142,142,245,62,52,12,1};

    for(int i=0;i<10;i++)
    {
        info.price=a[i];
        info.qty=a[i];
        //some logic to find the price and if found then simply add the qty



        //********This part of the code doesnt work(NO ERROR)*********
              iter=bar.find(info);//Find before insert
              info.qty+=(*iter).qty;//then add
       //******************************************

        bar.insert(info);
        //code to print the set
    }
    return 0;
}

So I want to find if the price is already present in the set, and if so I want to add the quantity.
e.g. Since 142 is added to the set, when it finds the next 142 in a it should add that to the existing entry.
I know how to do this with map but since it is a set of struct, i am not able to manipulate it

Final Desired Output:

Price...Qty
1...........1
12.........12
52.........52
62.........62
100.......100
120.......120
142.......284 ///Here it finds and then adds the qty
245.......245
500.......500

Upvotes: 0

Views: 343

Answers (1)

davmac
davmac

Reputation: 20631

As pointed out by others, access to items in a set is via a const reference so you cannot normally modify them. This problem is well suited to a map.

The reason why your code compiles is because one line is backwards:

          info.qty+=(*iter).qty;//then add

Should be:

          (*iter).qty+=info.qty;//then add

Just making this change will give a compilation error. If you must use a set, you can also mark the qty member mutable to avoid the error:

mutable int qty;

Using mutable for this would probably be considered bad practice by many, however. The issue is that any const reference to a data object now allows the qty member to be mutated.

Upvotes: 1

Related Questions