#include <map>
#include <iostream>
using namespace std;
//Map中的元素是自动按key升序排序
int main(){
map <int, int> m,m2,m3;
m.insert ( pair <int, int> ( 1, 233 ) );//insert() 插入
m.insert ( pair <int, int> ( 2, 666 ) );
m.insert ( pair <int, int> ( 6, 789 ) );
m2[10]=100;
m2[20]=200;
m3.insert ( pair <int, int> ( 30, 300 ) );
m.insert(m2.begin(), m2.end());//将区间[begin, end)中的值插入到 s 中。该区间应该是 map 类型的。
map <int, int>::iterator m_Iter;
for (m_Iter = m.begin( ); m_Iter != m.end( ); m_Iter++ )
cout << m_Iter->first<<" "<<m_Iter->second<<endl;
cout<< m[3] << endl ;//返回一个引用 指向键为 3 时的对应值。如果元素不存在,map会自动建立这个元素。
cout<< m.begin()->first << ' ' << m.begin()->second << endl ;//返回指向map头部的迭代器
cout<< m.rbegin()->first << ' ' << m.rbegin()->second << endl ;//返回指向map尾部的迭代器
cout<< m.end()->first << ' ' << m.end()->second << endl ;//返回指向map末尾的迭代器
cout<< m.count(3) << endl ;//返回 s 中键为 3 的具体数目。但对于 map 来说,返回值不是 0 就是 1。
//find() 返回指向键为 2 的元素的迭代器。如果不存在,则返回 m.end()。
cout<< m.find(2)->second << endl ;
map<int ,int>::iterator l_it;;
l_it=m.find(2);
if(l_it==m.end())
cout<<"we do not find 112"<<endl;
else cout<<"we find 112"<<endl;
//lower_bound() //返回键值>=给定元素的第一个位置
cout<< m.empty() << endl ;//判断映射是(1)否(0)为空映射。
cout<< m.size() << endl ;//返回映射的元素数量。
int e=3;
m.erase(e);//将键为 e 的元素删除。返回值为被删除的 e 的数量(对于 multimap 来说,被删除的可能不止一个元素)
}
STL-Map
最新推荐文章于 2023-08-22 22:20:23 发布