博客
关于我
22. 切勿直接修改set或multiset中的键
阅读量:732 次
发布时间:2019-03-21

本文共 1319 字,大约阅读时间需要 4 分钟。

就像所有标准关联容器一样,set和multiset都基于特定的顺序存储元素,而这种容器的正确行为正是建立在其原始有序的基础之上。如果对关联容器中的一个元素的值进行修改,那么新值可能不再处于正确的位置,从而破坏了容器的有序性。

由于map和multimap的元素类型为std::pair

,其中键的类型为const K,因此直接修改它们的值是不可行的。然而,对于set和multiset来说,元素类型为T而非const T

,因此可以通过修改元素的值来实现操作。

假设有一个雇员类:

class Employee{
public: ... const std::string& name() const; void SetName(const std::string& name); const std::string& title() const; void SetTitle(const std::string& title); int idNumber() const; ...}

要创建一个按id排序的set:

auto sortFunc = [](const Employee& lhs, const Employee& rhs) {
return lhs.idNumber() < rhs.idNumber(); };std::set
datas;

使用set或multiset进行排序时,只要不修改元素的排序依据(如id),则不会影响排序的正确性。由于set和multiset的键为T而非const T,因此可以对它们的值进行修改而不至于破坏容器的有序性。

需要注意的是,一定在修改set或multiset的元素时要小心不要修改键的部分。键的修改会影响容器的排序,从而导致后续操作产生不确定的结果,这一错误将完全由你承担。

如果想以一种总是可行而且安全的方式来修改set、multiset、map或multimap中的元素,可以按照以下步骤进行操作:

  1. 找到你想要修改的元素在容器中的位置
  2. 创建一个对应元素的拷贝对象
  3. 对拷贝对象进行修改,使其具备你期望在容器中看到的值
  4. 从容器中删除原有的元素
  5. 使用常数时间复杂度的插入方式添加新的元素(如果需要保持插入效率,可以选择“提示”_hint的形式插入)

例如,要将set中的键"WorldPeace"修改为"HelloWorld",可以按照以下步骤操作:

auto iter = datas.find("WorldPeace");if (iter != datas.end()){
auto curData = *iter; curData.setName("HelloWorld"); datas.erase(iter); datas.insert(curData);}

转载地址:http://waqgz.baihongyu.com/

你可能感兴趣的文章
Orcale表被锁
查看>>
svn访问报错500
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>
os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
查看>>