0

I am using a multiset to hold Building instances, and I want to order by building height (desc order), and using a lambda express to define it. This part seems ok.

My confusion is about this line, buildings.erase(delta);, after this line is executed, a building is removed from multiset, my expected behavior is only both id and height are equal, the building z is removed. Wondering why this line buildings.erase(delta); will remove the building z in my example?

And is it possible to define a multiset ordered by height, but remove only when both id and height are equal?

#include <iostream>
#include <set>
using namespace std;

struct Building {
    int id;
    int height;
    Building(int i, int h) {
        id = i;
        height = h;
    }
};

int main() {
    auto f = [](Building a, Building b) { return a.height > b.height; };
    multiset<Building, decltype(f)> buildings(f);
    Building x(1,100);
    Building y(2, 200);
    Building z(3, 300);
    buildings.insert(x);
    buildings.insert(y);
    buildings.insert(z);
    cout << buildings.size() << endl; 
    Building delta(4, 300);
    buildings.erase(delta);
    cout << buildings.size() << endl; 
}
Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 4
    Your comparison object says that two objects are equivalent if their heights are equal. Erasing `delta` therefore deletes every building whose height is 300. It sounds like what you really want is a `multimap` keyed by height. – Raymond Chen Oct 16 '17 at 04:26
  • Thanks @RaymondChen, the comparison for ordering, and comparison for erase needs to be the same function for multiset? – Lin Ma Oct 16 '17 at 05:19
  • 1
    `multiset` takes only one comparison function. That comparison function is used to determine which objects are identical. If your comparison function compares by height, then all objects with the same height are considered the same. – Raymond Chen Oct 16 '17 at 17:27
  • Thanks @RaymondChen, the comparison function returns bool to indicate smaller or greater, but how to indicate equal (for the use case of erase)? – Lin Ma Oct 17 '17 at 06:37
  • Think back to math class. If it's not less than and not greater than,then it is equal. – Raymond Chen Oct 17 '17 at 14:32

0 Answers0