關於容器map的操作代碼

#include
#include<map>
#include<iterator>
using namespace std;


int main()
{
typedef map<int,string> M;
M my_map;


/*-----say how to insert value in the map*/


//Example for some way to insert value in the map
//1.the first is the subscript operation
my_map[1]="frist";


//2.the second way
my_map.insert(M::value_type(2,"second"));


//3.
my_map.insert(pair<int,string>(3,"three"));


//4.
my_map.insert(make_pair(4,"four"));


/*-----show the map-----*/
M::iterator It=my_map.begin(); //define a iterato
//printf the value of map
cout<<"the value of map"<<endl;
while(It!=my_map.end())
{
  cout<<It->first<<"--"<<It->second<<endl;
  It++;
}
cout<<endl;




/*-----search a value in the map----*/
//1.subscript operation


string str=my_map[2];         //search a value of the key is 2
my_map[2]="second_change";    //change the value of  the key is 2
cout<<"first search way:the change value map[2]: "
    <<my_map[2]<<endl;


//2.through the iterator
M::iterator search_map=my_map.find(3);
str=search_map->second;
search_map->second="find you";
cout<<"second search way:the change value :"<<search_map->second<<endl;


//!!!!!   BUT be careful the subscript operation
//if the key not in the map,it can insert a new key in the map
//the value is  default value
str=my_map[5];
It=my_map.begin();
while(It!=my_map.end())
{
   cout<<It->first<<"__"<<It->second<<endl;
   It++;
}
cout<<endl;


/*-----delete the value----*/
//delete of the iterator
my_map.erase(search_map);
//delete of the value
my_map.erase(4);
It=my_map.begin();
while(It!=my_map.end())
{
   cout<<It->first<<"--"<<It->second<<endl;
   It++;
}
cout<<endl;


/*-----other way in map-----*/
//return count
cout<<"my_map size is:"<<my_map.size()<<endl;
//clear the map
my_map.clear();
//contrast the map
if(my_map.empty())
  cout<<"the map is clear,now is empty"<<endl;

getchar();
return 0;

}


result:

the value of map
1--frist
2--second
3--three
4--four


first search way:the change value map[2]: second_change
second search way:the change value :find you
1__frist
2__second_change
3__find you
4__four
5__


1--frist
2--second_change
5--


my_map size is:3
the map is clear,now is empty

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章