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

C++ 学习小程序之 map 的用法

2015-11-06 16:17 639 查看
1. map::at

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: