C++ 学习小程序之 map 的用法
2015-11-06 16:17
639 查看
1. map::at
2. make_pair example
3. map::begin/end
4. map::insert(C++98)
#include <iostream> #include <string> #include <map> using namespace std; int main(){ map<string, int> mymap = { {"alpha", 0}, {"beta", 0}, {"gamma", 0}}; mymap.at("alpha") = 10; mymap.at("beta") = 20; mymap.at("gamma") = 30; for (auto& x:mymap){ cout<<x.first<<": "<<x.second<<'\n'; } return 0; }
2. make_pair example
// make_pair example #include <utility> // std::pair #include <iostream> // std::cout int main () { std::pair <int,int> foo; std::pair <int,int> bar; foo = std::make_pair (10,20); bar = std::make_pair (10.5,'A'); // ok: implicit conversion from pair<double,char> std::cout << "foo: " << foo.first << ", " << foo.second << '\n'; std::cout << "bar: " << bar.first << ", " << bar.second << '\n'; return 0; }
3. map::begin/end
// map::begin/end #include <iostream> #include <map> int main () { std::map<char,int> mymap; mymap['b'] = 100; mymap['a'] = 200; mymap['c'] = 300; // show content: for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it) std::cout << it->first << " => " << it->second << '\n'; return 0; }
4. map::insert(C++98)
// map::insert(C++98) #include <iostream> #include <map> using namespace std; int main () { map<char,int> mymap; // first insert function version (single parameter): mymap.insert ( pair<char,int>('a', 100) ); mymap.insert ( pair<char,int>('z', 200) ); pair<map<char, int>::iterator, bool> ret; ret = mymap.insert (pair<char,int>('z',500)); if (ret.second == false){ cout<<"element 'z' already existed"; cout<<"with a value of " << ret.first->second << '\n'; } //second insert function version (with hint position): map<char, int>::iterator it = mymap.begin(); mymap.insert (it, pair<char, int>('b',300)); // max efficiency inserting mymap.insert (it, pair<char, int>('c',400)); // no max efficiency inserting //third insert function version (range insertion): map<char,int> anothermap; anothermap.insert(mymap.begin(),mymap.find('c')); // showing contents: cout<<"mymap contains: \n"; for (it = mymap.begin(); it!= mymap.end(); ++it) cout<<it->first<<"=>"<<it->second<<'\n'; cout<<"anothermap contains: \n"; for(it=anothermap.begin(); it!=anothermap.end();++it) cout<<it->first<<"=>"<<it->second<<'\n'; return 0; }
相关文章推荐
- [leetcode][C++]Find Median from Data Stream
- Leap Motion自带Sample之详解_Win/C++版本
- C语言练习作业(一)
- MFC 初步:写一个带窗口的Windows程序
- c++ ui 库
- Bulls and Cows
- C语言可变参数
- c语言学习之基础知识点介绍(十七):写入读取结构体、数组、结构体数组
- C语言习题1
- 谁说C++语言超级难学?师兄教你四招搞定C++
- 内存的申请与释放
- C语言:存取结构体成员的点运算符(.)和箭头运算符(->)的区别
- [BCB] C++ BUILDER 绘图 随机生成图形
- RSA算法详解及C语言实现
- c语言学习之基础知识点介绍(十六):文件操作
- C++, Java和C#的编译过程解析
- c++输入输出格式的控制
- C语言免安装TCC编译环境的搭建
- C++内存分配方式详解——堆、栈、自由存储区、全局/静态存储区和常量存储区
- 插入排序