c++ - 在 C++ 中查找一组结构

标签 c++ set

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 constdata 对象的引用现在允许改变 qty 成员。

关于c++ - 在 C++ 中查找一组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47405331/

相关文章:

python - 列表中多个集合的交集

java - 如果我更改 HashSet 中的对象会怎样?

c++ - Qt 布局以自身为中心

c++ - 多线程 C 程序中的信号量互斥并发问题

c++ - 将 std::vector 的拷贝附加到其自身的末尾

Python:集合和set.intersection - 输出的随机顺序?

c++ - 为什么 STL_tree.h 中的 end() 返回对迭代器对象的引用,而 begin() 返回对象?

C++ 访问变量而不使用其名称?

c++ - 将 C++ 与 Objective-C 结合使用,如何修复 "Conflicting declaration ' typedef int BOOL'"?

algorithm - 如何使用逻辑推理分析策划类游戏