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

时间:2021-07-19 01:58:05

1. map::at

 #include <iostream>
#include <string>
#include <map>
using namespace std; int main(){
map<string, int> mymap = {
{"alpha", },
{"beta", },
{"gamma", }}; mymap.at("alpha") = ;
mymap.at("beta") = ;
mymap.at("gamma") = ; for (auto& x:mymap){
cout<<x.first<<": "<<x.second<<'\n';
} return ;
}

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 (,);
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 ;
}

3. map::begin/end

 // map::begin/end
#include <iostream>
#include <map> int main ()
{
std::map<char,int> mymap; mymap['b'] = ;
mymap['a'] = ;
mymap['c'] = ; // show content:
for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n'; return ;
}

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', ) );
mymap.insert ( pair<char,int>('z', ) ); pair<map<char, int>::iterator, bool> ret;
ret = mymap.insert (pair<char,int>('z',));
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',)); // max efficiency inserting
mymap.insert (it, pair<char, int>('c',)); // 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 ;
}