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;
}
所以我想知道价格是否已经存在于 set
中,如果是,我想添加数量。
例如由于 142 已添加到 set
中,因此当它在 a
中找到下一个 142
时,它应该将其添加到现有条目中。
我知道如何使用 map 执行此操作,但由于它是一组结构,我无法操作它
最终期望的输出:
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
最佳答案
正如其他人所指出的,对集合中项目的访问是通过 const
引用进行的,因此您通常无法修改它们。这个问题很适合 map 。
你的代码编译通过的原因是因为有一行向后:
info.qty+=(*iter).qty;//then add
应该是:
(*iter).qty+=info.qty;//then add
仅进行此更改会产生编译错误。如果你必须使用集合,你也可以将qty
成员标记为可变以避免错误:
mutable int qty;
然而,为此使用 mutable
可能被许多人认为是不好的做法。问题是 any const
对 data
对象的引用现在允许改变 qty
成员。
关于c++ - 在 C++ 中查找一组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47405331/