find value in multiset and erase if exists

141 Views Asked by At

I have code like this:

// implementation of multiset
#include <condition_variable> // std::condition_variale
#include <iostream>
#include <iterator>
#include <set>
#include <thread>
#include <algorithm>
#include <mutex>


using namespace std;

class Rect{
public:
        double height;
        double width;
        double area;
        string name;

        friend ostream& operator<<(ostream& os, const Rect& r);
};

ostream& operator<<(ostream& os, const Rect& r)
{
    os << r.area << " " << r.name;
    return os;
}

struct LessArea
{
    bool operator ()(const Rect& lhs, const Rect& rhs) const
    {
        return lhs.area < rhs.area;
    }
};

std::multiset<Rect, LessArea> rects;

I am producing data (in a thread but probably not relevant). Before I insert the new Rect, I would like to search the multiset and if the Rect with that name exist, delete it. Then add new one:

produceData()
{
  const string arrayString[4] = {"C", "B", "N", "A"};
  int RandIndex = rand() % 4; //generates a random number between 0 and 3
  string name = arrayString[RandIndex];

  int randomNumber1 = (int)(rand() % 1000);
  int randomNumber2 = (int)(rand() % 1000);
  int randomNumber3 = (int)(rand() % 1000);

  Rect value = {randomNumber1, randomNumber2, randomNumber3, name};

  // I would like to delete a rect if the name already exists regardless of other values
  rects.erase(s.lower_bound(value)); // This won't work because it is matching ALL fields


  // Add new value
  addToMultiSet(value);
}

How do I search the multiset and delete the element if the name is already contained?

EDIT 1

class Rect{
public:
        double height;
        double width;
        double area;
        string name;

        bool operator == ( const Rect & rhs ) const { return ( name == rhs.name ); }
        friend ostream& operator<<(ostream& os, const Rect& r);
};

...

multiset<Rect>::iterator ceItr = rects.find( value );

if(ceItr != rects.end())
{
    rects.erase(ceItr);
}
0

There are 0 best solutions below