Greetings,
I am using a set<> of classes, where one or more members of the structure are used to determine sorting order. But not all members. This happens to work out very nicely when I have have to maintain a table for SNMP--I just define operator<() to be the SNMP ordering function. All that works just fine.
However, I find that when I need to update an element of the set (not the indices used by operator<) I cannot as I get a const reference or iterator. Fine, that's the way set<> works, by assuming that all parts of the type are used in the sorting function. But it means that doing an update of an existing element is awkward; I must remove the original entry and then insert a new one to replace it. And these 2 versions have exactly the same indices.
Below is a trimmed down version of the class and an update function. It works, but it just seems like it is unreasonably inefficient to have to:
- Find if there is an existing element already
- Remove that element
- Insert a new element that winds up in exactly the same position!
So, finally, my question is: Is there a standard paradigm for updating a member of a set<>?
I suspect I am just missing something. Suggestions appreciated.Code:class ENTPHYSICALENTRY : public PHYSICAL_ENTITY_STRUCT { public: ENTPHYSICALENTRY(void) // default constructor { initEmptyEntry(); } ~ENTPHYSICALENTRY(void) {} void initEmptyEntry(void); ENTPHYSICALENTRY(const PHYSICAL_ENTITY_STRUCT &t) { CopyModule(&t); } ENTPHYSICALENTRY & operator= (const ENTPHYSICALENTRY &t) { if(&t != this) // avoid copying to one's self { CopyModule(&t); } return(*this); } void CopyModule(const PHYSICAL_ENTITY_STRUCT *t); bool operator< (const ENTPHYSICALENTRY &r) const { if(this->entPhysicalIndex < r.entPhysicalIndex) return(true); return(false); } }; typedef std::set<ENTPHYSICALENTRY> ENTPHYSICALSET; typedef ENTPHYSICALSET::iterator ENTPHYSICALITER; ENTPHYSICALSET entPhysicalTable; // This is the actual table of entPhysicalEntry // Insert new entry or replace old entry with more recent version STATUS UpdateEntityEntry(ENTPHYSICALENTRY &entry) { // insert() will not overwrite, so we must remove and insert if it already exists. // And erase() crashes if the entry doesn't already exist. ENTPHYSICALITER iter = entPhysicalTable.find(entry); if(iter != entPhysicalTable.end()) { (void)entPhysicalTable.erase(iter); } pair<ENTPHYSICALITER, bool> insertRetval = entPhysicalTable.insert(entry); if(ASSERT(insertRetval.second)) // second is a bool which is true if the insert succeeded { return ERROR; } blah, blah, blah, ... }
Thanks.
-- Harold



LinkBack URL
About LinkBacks



