STL_map_映射

构造一个map的方法是

map < string, int> m;
map < int, string> m;
map < string, string> m;

在< >中指定一对键(key)值(value)的类型.
在map中可以通过重载了的[]来通过键访问值

m[“a”] = 1;
m[“hello”] = 666;

map常用函数如下

size()      //返回map中元素数
clear()      //清空map
begin()      //返回指向map开头的迭代器
end()      //返回指向map末尾的迭代器
insert( (key, val) )      //向map中擦汗如元素(key, val)
erase(key)      //删除含有key的元素
find(key)      //搜索与key一致的元素, 并返回指向该元素的迭代器.
           //没有与key一致的元素, 则返回末尾end() 

map和set一样通过平衡二叉搜索树实现, 因此元素的插入, 删除, 搜索以及”[ ]”运算符的复杂度都为O(logn)

使用迭代器顺序访问每一对键和值

map< string, int> :: iterator it = m.begin();
cout << it->first << endl;      //print the key
cout << it->second << endl;      //print the value

也可以使用STL提供的pair(结构体模板) 对map的元素进行访问
pair详细说明

pair< string, int> item = *it;
cout << item.first;       //the key;
cout << item.second;      //the value
item = make_pair(“heo”, 23);

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map <string, int> m;
    m["a"] = 97;
    m["b"] = 98;
    map <string, int> :: iterator it = m.begin();
    cout << it->first << ' ' << it->second << endl;  //print the key and the value
    it++;
    pair <string, int> item = *it;
    cout << item.first << ' ' << item.second << endl;
}

map的键值的唯一性怎么样?

test 1:
向一个已有(“a”, “A”)的map中再添加, map不变, 可知相同的元素是唯一的

test 2:
向一个有(“a”, “A”)的map中添加(“a”, “aa”), map还是不变, 这是为什么? 它内部检测是否唯一的机制难道是如果键存在, 那么这个insert就失效?

所以修改值的方法只能是用迭代器的方法直接修改

常用函数用法代码::

#include <iostream>
#include <map>

using namespace std;

int main()
{
    //construct a map
    map < string, string > alpha;

    //the size
    cout << "the size is " << alpha.size() << endl;

    //three ways to insert
    alpha.insert(make_pair("a", "A"));
    alpha.insert(pair<string, string>("b","B"));
    pair<string, string> pp("c", "C");
    alpha.insert(pp);

    //cannot insert
    alpha.insert(make_pair("a", "aa"));
    cout << "now the size is " << alpha.size() << endl;

    //use the iterator to traversal
    map <string, string> :: iterator it = alpha.begin();
    while(it != alpha.end()) {
        cout << "the first is " << it->first << " and ";
        cout << "the second is " << it->second << endl;
        it++;
    }

    //use the fuction of erase
    alpha.erase("b");

    //traversal again
    it = alpha.begin();
    cout << endl;
    while(it != alpha.end()) {
        cout << "the first is " << it->first << " and ";
        cout << "the second is " << it->second << endl;
        it++;
    }

    //use find
    if(alpha.find("b") == alpha.end()) {
        cout << "there is no the key---\"b\"\n";
    }
    if(alpha.find("c") != alpha.end()) {
        cout << "yes, there is , and it is ";
        cout << alpha.find("c")->second << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值