map
map是一種鍵值對容器。
特點:鍵唯一且基本數(shù)據(jù)類型按從小到大升序排列。
使用方法如下
#include <iostream> //輸入輸出頭文件
#include <map> //map頭文件
using namespace std; //命名空間
map<char,int> m; //聲明一個名為m的map
int main(){
/*向map中插入數(shù)據(jù)*/
m.insert(pair<char, int>('b', 3)); //以pair的方式插入數(shù)據(jù)
m.insert(pair<char, int>('a', 2));
m['d'] = 5; //普通方式插入數(shù)據(jù)
m['c'] = 3;
m['e'] = 6;
/*刪除map中的數(shù)據(jù)*/
char ch = 'e'; //聲明字符變量
m.erase('d'); //刪除元素 d
m.erase(ch); //通過變量名刪除
m.erase(m.begin()); //通過迭代器刪除
/*遍歷map(注:m['e'] = 6中,e為鍵,6為值)*/
map<char, int>::iterator iter; //聲明一個迭代器
for(iter = m.begin(); iter != m.end(); iter++){ //使用迭代器遍歷map
cout << iter->first << " "; //輸出 鍵
cout << iter->second << endl; //輸出 值
}
/*count方式判斷元素是否存在*/
if(m.count('d') == 1){ //返回值0表示沒有,1表示有
cout << "d 在map中" << endl;
}else{
cout << "d 不在map中" << endl;
}
/*find方式判斷元素是否存在*/
if(m.find('d') != m.end()){ //沒有找到返回end();
cout << "d 在map中" << endl;
}else{
cout << "d 不在map中" << endl;
}
/*修改map中的值*/
m['d']++; //將d元素的值加1
/*map的容量相關(guān)用法*/
if(m.empty()){ //map為空返回1,否則返回0
cout << "map為空!" << endl;
}else{
cout << "map不為空!" << endl;
}
cout << m.size() << endl; //輸出map的大小
return 0;
}
set
特點:元素唯一且默認從小到大升序排列
使用方法如下
#include <iostream> //輸入輸出頭文件
#include <set> //set頭文件
using namespace std; //命名空間
set<int> s; //聲明一個set
int main(){
/*向set中插入數(shù)據(jù)*/
s.insert(1); //插入數(shù)據(jù)
s.insert(1); //插入重復(fù)數(shù)據(jù)(只保存一個)
s.insert(2);
s.insert(3);
s.insert(4);
/*刪除set中的數(shù)據(jù)*/
int tmp = 1; //聲明一個變量
s.erase(1); //直接刪除數(shù)據(jù)
s.erase(tmp); //通過變量名刪除
s.erase(s.begin()); //通過迭代器刪除
/*count方式判斷元素是否存在,與map類似*/
if(s.count(2) == 1){ //返回值0表示沒有,1表示有
cout << "2 在set中" << endl;
}else{
cout << "2 不在set中" << endl;
}
/*find方式判斷元素是否存在*/
if(s.find(2) != s.end()){ //沒有找到返回end();
cout << "2 在set中" << endl;
}else{
cout << "2 不在set中" << endl;
}
/*遍歷set*/
set<int>::iterator it;
for(it = s.begin(); it != s.end(); it++){ //只能使用 != 判斷
cout << *it << endl; //注意和map的區(qū)別
}
/*set也有empty()和size()兩個函數(shù),與map相同*/
return 0;
}
queue
與普通隊列一樣,這是STL中提供的方法
使用方法如下
#include <iostream> //輸入輸出頭文件
#include <queue> //隊列頭文件
using namespace std; //命名空間
queue<int> q; //聲明一個名為q的隊列
int main(){
/*在隊列末尾增加一個元素*/
q.push(2);
q.push(3);
q.push(2);
q.push(3);
/*刪除隊列第一個元素*/
q.pop();
/*查看隊列的元素*/
cout << q.front() << endl; //輸出隊列第一個元素(不刪除)
cout << q.back() << endl; //輸出隊列最后一個元素(不刪除)
cout << q.size() << endl; //輸出隊列的大小
/*判斷隊列是否為空*/
if(q.empty()){ //為空返回1,否則返回0
cout << "隊列為空!" << endl;
}else{
cout << "隊列不為空!" << endl;
}
return 0;
}
stack
與平時提到的棧一樣,這里是STL中棧的使用方法
使用方法如下
#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
int main(){
/*向棧頂增加元素*/
s.push(3);
s.push(4);
s.push(7);
s.push(0);
/*移除棧頂元素*/
s.pop();
/*輸出棧頂元素(不刪除)*/
cout << s.top() << endl;
/*輸出棧的大小*/
cout << s.size() << endl;
/*判斷隊列是否為空的方法與queue相同*/
return 0;
}