您的位置:首页 > 编程语言 > C语言/C++

STL控件的使用

2015-06-14 09:50 429 查看
1. list使用:

数据结构的双链表一般来说对应stl中的list,并且list几乎提供了双链表操作的所有方法

常见的list操作有(至少是我用到的):

remove,

push_back,

#include<iostream>
#include <list>
using namespace std;

struct node
{
int key;
int val;
};

void main()
{
node * nn;
list<node*> ll;

for(int i=0; i<5; i++)
{
node * tmp=new node;
tmp->key=i;
ll.push_back(tmp);
if(i==3)
nn=tmp;
}
ll.remove(nn);//删除元素,单但是不会释放空间,因为remove以及erase等操作只是破坏了链表的结构,对于指针类型,不会释放外部申请的空间,因此下边的打印操作可以继续执行,且不会产生段错误

list<node*>::iterator it;
cout<<"all the data in the list is:"<<endl;
for(it=ll.begin(); it!=ll.end(); it++)
{
cout<<(*it)->key<<endl;
}
cout<<endl<<"after delete the node the original pointer's space is still exist"<<endl;
cout<<nn->key<<endl<<endl;

cout<<"ll's size is: "<<ll.size()<<endl;

}


运行结果:

#include<set>

using namespace std;

int main(){
set<int> ss;
for(int i=2; i<11; i++){
ss.insert(i);
}

for(set<int>::iterator it=ss.begin(); it!=ss.end(); it++){
cout<<*it<<'\t';
}
cout<<endl;

        //注意,这里不能直接在for语句中加it++,现在本人发现的最安全的方法是下面的使用方法
for(set<int>::iterator it=ss.begin(); it!=ss.end();){
if(*it==5){
ss.erase(it++);//正确方式
}
else{
cout<<*it<<'\t';
it++;
}
}
cout<<endl;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  stl 链表 list c++