博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
std::set 中内部元素有序条件删除的理解
阅读量:4501 次
发布时间:2019-06-08

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

std::set 中内部元素有序条件删除的理解

1. std::set中的元素是有序排列的

  注意:Set集合中的元素通过iterator的引用,但是不能修改。

元素排序:

(1)元素中实现比较operator < ,

(2)Set构造中,输入仿函数(实现元素比较排序)

  基于上述的规则,因此:如果要更新Set中元素的修改,只能将元素erase删除,然后将更新后的元素insert中,则自动保证insert中的相应位置

 

  

2. 如果Set中的元素是object,不是指针。

  删除元素的代码:

  因为, 如果用iterator删除当前所指的元素,只能用s.erase(it++) 这样的形势, 在it删除之后,其实已经更新为下一个的迭代器了。

#include 
using std::set; int main(int argc,char *argv[]){ set
s; set
::iterator it; s.insert(1); s.insert(2); s.insert(3); for(it=s.begin();it!=s.end();){ if((*it)%2==0) s.erase(it++); else it++; } system("pause"); return 0;} STL/C++__中 set(集合)  删除元素, set的erase不会返回迭代器,这点需要注意。

3. 如果Set中的元素是:指针。

  因为元素是指针,因此同样要要提供:比较函数。

  这样可以突破了:虽然不能修改元素内容,因为元素指针不能修改,但是元素指针所指的内存可以修改。但是注意:此时的“顺序”不能保证

  注意,在Set中,插入指针类型,如果释放资源,可以直接delete (*it), 注意, 此时的it还是有效的,可以使用it++

#include "stdafx.h"#include 
#include
using namespace std;class Name{public: Name(int _a, int _b) :a(_a), b(_b){}; int a; int b;};class CMP{public: bool operator()(Name* _p1, Name* _p2) { if (_p1->a < _p2->a) return true;//前一个元素,小于,后一个元素,升序 return false; }};typedef std::set
ContainerType;int _tmain(int argc, _TCHAR* argv[]){ ContainerType container; container.insert(new Name(44, 22)); container.insert(new Name(33, 22)); container.insert(new Name(11, 22)); container.insert(new Name(42, 22)); container.insert(new Name(99, 22)); container.insert(new Name(66, 22)); ContainerType::iterator it; //显示 for (it = container.begin(); it != container.end(); ++it) { //更新内部状态 cout << (*it)->a << " " << (*it)->b << endl; } cout << "---------------------" << endl; for (it = container.begin(); it != container.end(); ++it) { //更新内部状态 if ((*it)->a > 50) (*it)->a -= 10; else { (*it)->a += 1000; } } container.insert(new Name(0, 22)); container.insert(new Name(300, 22)); //显示 for (it = container.begin(); it != container.end(); ++it) { //更新内部状态 cout << (*it)->a << " " << (*it)->b << endl; } //释放资源 for (it = container.begin(); it != container.end(); ++it) { //更新内部状态 delete *it; } system("pause"); return 0;}

  

 

   

 

 

 

 

 

 

endl;

转载于:https://www.cnblogs.com/icmzn/p/9669613.html

你可能感兴趣的文章
jQuery(属性操作)
查看>>
Python之路【第九篇】:Python面向对象
查看>>
background和background-image一点小区别
查看>>
ASCII码对照表
查看>>
HackerRank "Training the army" - Max Flow
查看>>
jquery next()方法
查看>>
深入剖析js命名空间函数namespace
查看>>
SQLHelper
查看>>
用标准Struts2+mvc写的用户管理
查看>>
Cocos2d-x 3.0 编译出错 解决 error: expected &#39;;&#39; at end of member declaration
查看>>
Ubuntu12.04下载Repo
查看>>
python基础教程_学习笔记10:异常
查看>>
MATLAB——scatter的简单应用
查看>>
linux下复制粘贴快捷键
查看>>
什么是对象
查看>>
记录开发小程序
查看>>
WinSock服务程序
查看>>
巴西柔术第五课:过腿
查看>>
文件的操作
查看>>
网上图书商城项目学习笔记-007登录功能实现
查看>>