博客
关于我
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/

你可能感兴趣的文章
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>