随感而发

杂七杂八

统计

留言簿(13)

阅读排行榜

评论排行榜

STL_Map的简单实用

今天学了STL中Map的简单操作,学的很肤浅,呵呵,目前我只用到这些,还需要继续努力。呵呵。如果要查阅MSDN的话,关键字可以用map class.呵呵。还有多看一下其它介绍STL的书。也刚刚转载了博客园一个前辈的map资料,很不错。所以这里就直接奉上源代码:注意[]的操作,他是一个插入和修改,查找合并的过程,如果没有找到,他会插入一个默认元素的。如果要修改,可以直接用[]做修改。呵呵。
#include <iostream>
#include
<map>
using namespace std;


int main()
{
    typedef map
<intint> Map_DInt;
    typedef pair
<intint> Map_Pair;

    Map_DInt map1;

    
//empty是检测map是否为空
    if (map1.empty())        //检测是否为空如果为空,输出
    {
        cout 
<< "empty\n";
    }


    map1[
3= 30;        //因为map重载了[]可以通过[]直接添加数据和查找数据
    map1.insert(Map_DInt::value_type(4,40));    //添加数据4(key), 40(value)
    map1.insert(Map_Pair(110));        //添加数据1,10

    
//遍历节点,并输出对应的key和value
    for (Map_DInt::iterator it1 = map1.begin(); it1 != map1.end(); ++it1)
    
{
        cout 
<< "Key:" << it1->first <<" Value:" <<it1->second << endl;
    }


    
//[]也可以直接用于查找,但是如果没有找到,他会默认加一个值进去的
    Map_DInt::iterator it1;

    it1 
= map1.find(5);        //查找key 为5的数据
    if (it1 != map1.end())    //如果找到,则输出他的数据
    {
        cout 
<< it1->second << endl;
    }

    
else                    //否则输出找不到
    {
        cout 
<< "Not Found\n";
    }


    
if (map1[5!= 0)
    
{
        cout 
<< map1[5<< endl;
    }

    
else
    
{
        cout 
<< "Not Found\n";
    }


    it1 
= map1.find(5);        //查找key 为5的数据
    if (it1 != map1.end())    //如果找到,则输出他的数据
    {
        cout 
<< it1->second << endl;
    }

    
else                    //否则输出找不到
    {
        cout 
<< "Not Found\n";
    }

    
    map1[
5= 50//更改相应的值

    it1 
= map1.find(5);        //查找key 为5的数据
    if (it1 != map1.end())    //如果找到,则输出他的数据
    {
        cout 
<< it1->second << endl;
    }

    
else                    //否则输出找不到
    {
        cout 
<< "Not Found\n";
    }


    size_t nNum 
= map1.erase(5);    //删除数据

    map1.clear();        
//清楚所有数据

    system(
"pause");
    
return 0;
}


posted on 2009-04-05 18:11 shongbee2 阅读(469) 评论(0)  编辑 收藏 引用 所属分类: c/c++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理