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

C++容器

2015-07-17 21:24 357 查看
map和multimaps: 

1、头文件都是#include<map>,并且都按关键字递增排序

2、迭代器map<int,string>::iterator iter;   iter->first  =>key;iter->second =>elem;这里迭代器要用"->"

3、对于multimap.find(key)查找第一个key键,并且返回其迭代器;e而删除erase(key)则会删除所有的key键;

4、不能通过以下方式删除其具有某value值的元素;

for(pos=amap.begin();pos!=amap.end();pos++){

if(pos->second = 2){

amap.erase(pos);//会使pos不再成为一个有效的迭代器

}

正确方式是使用以下临时迭代器

map<string,int>::iterator temp;

for(pos=amap.begin();pos!=amap.end();pos++){

if(pos->second = 2){

temp = pos;

amap.erase(temp);

break;

}

}

5、map<key,elem,op>  op可以是greater<key>或less<key>排序顺序

当key是自己定义的结构体时就会出错;

struct stu{

int num;

float  height;

bool operator<(const stu & x ) const{

teturn num<x.num

}

}

map<stu,int> atumap;

双向链表 List容器:

int data[6]={3,5,7,9,2,4};
list<int> lidata(data, data+6);
lidata.push_back(6);




1、unique()删除相邻重复元素(断言已经排序,因为它不会删除不相邻的相同元素)

c1.unique(); //假设c1开始(-10,10,10,20,20,-10)则之后为c1(-10,10,20,-10)

2、用STL的通用算法count()来统计list中的元素个数
int cNum;
char ch = ’b’;
cNum = count(cList.Begin(), cList.end(), ch); //统计list中的字符b的个数

3、使用STL通用算法find()在list中查找对象
list<char >::iterator iter = find(cList.begin(), cList.end(), ‘c’);
If (FindIterator == cList.end())
printf(“not find the char ‘c’!”);
else  printf(“%c”, * iter);
4、remove(val)函数删除链表中所有值为val的元素
reverse()函数把list所有元素倒转。
splice()函数把lst连接到pos的位置 void splice( iterator pos, list &lst );
swap()函数交换lst和现链表中的元素。void swap( list &lst );
priority_queue
对于自定义类型,则必须自己重载 operator< 或者自己写仿函数
#include <iostream>  
#include <queue>  
using namespace std;  
struct Node{  
    int x, y;  
}node;  
 bool operator<( Node a, Node b){  
    if(a.x==b.x) return a.y>b.y;  
    return a.x>b.x;  
}  
 int main(){  
    priority_queue<Node>q;  
    for(int i=0;i<10;i++){  
        node.x=i;  
        node.y=10-i/2;  
        q.push(node);  
    }     
    while(!q.empty()){  
        cout<<q.top().x <<' '<<q.top().y<<endl;  
        q.pop();  
    }  
    return 0;  


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