提问人:Ivan 提问时间:9/24/2022 最后编辑:Ivan 更新时间:9/25/2022 访问量:115
在多集中查找值并擦除(如果存在)
find value in multiset and erase if exists
问:
我有这样的代码:
// 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;
我正在生成数据(在线程中,但可能不相关)。在我插入新的之前,我想搜索 如果存在该名称,则为它。然后添加新的:Rect
multiset
Rect
delete
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);
}
如果已经包含,我该如何删除该元素?search
multiset
name
编辑 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);
}
答: 暂无答案
评论
multiset
multiset
set
multiset
Rect
Rect
name
Rect