Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Incrementing a map item with non default constructor

I have list of boxes with a number of a given product in each and I want to know how many items i have of each product.

I can solve this as:

#include <iostream>
#include <unordered_map>
#include <vector>

struct Item {
    int id;
    int count{0};
};

int main() {
    std::unordered_map<int, Item> products;
    std::vector<std::pair<int, int>> boxes {
        {1, 4}, {2, 2}, {1, 2}, {3, 1}, {1, 5}};
    for (const auto& [id, count]: boxes) {
        auto search{products.find(id)};
        if (search !=products.end()) { 
            search->second.count += count;
        } else {
            products.insert({id, {id, count}});
        }
    }

    for (const auto& [id, product]: products) {
        std::cout << product.id << ": " << product.count << std::endl;
    }
}

This correctly produces:

3: 1
1: 11
2: 2

Now, I'd like something closer to what I can do with types having a default constructor:

#include <iostream>
#include <unordered_map>
#include <vector>

struct Item {
    int id;
    int count{0};

    Item& operator+=(const int rhs)
    {
        count += rhs;
        return *this;
    }
};

int main()
{
    std::unordered_map<int, Item> products;
    std::vector<std::pair<int, int>> boxes {
        {1, 4}, {2, 2}, {1, 2}, {3, 1}, {1, 5}};
    for (const auto& [id, count]: boxes) {
        products[id] += count;
    }

    for (const auto& [id, product]: products) {
        std::cout << product.id << ": " << product.count << std::endl;
    }
}

But now I get:

0: 1
0: 11
0: 2

This syntax looks very readable to me, but the result is -- of course -- not what I was looking for.

My question:

For the case where most actions will be an increment and not an insert, is there a better solution -- one is that more comfortable to read -- than the one at the top of this post?

Something between the two code samples?

Comments