C++学习(1)--map

map的官方定义:

Map
Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.

In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. The types of key and mapped value may differ, and are grouped together in member type value_type, which is a pair type combining both:

  typedef pair<const Key, T> value_type; 


Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.

The mapped values in a map can be accessed directly by their corresponding key using the bracket operator ((operator[]).

Maps are typically implemented as binary search trees.

总体而言:

      map一种存储key—value的关联容器。底层实现一般为红黑树。也就是说,map其实是将插入的内容根据key值进行了排序。

map的插入方法

#include <iostream>
#include <map>

int main()
{
    std::map<int, std::string> my_map;

    my_map.insert(std::pair<int, std::string>(5, "abcd"));
    my_map.insert(std::map<int, std::string>::value_type(6, "abcde"));
    my_map[7] = "abcdef";
    my_map[1] = "ab";

    for(auto it = my_map.begin(); it != my_map.end(); it++)
    {   
        std::cout << "key:" << it->first << "\tvalue:" <<  it->second << std::endl;
    }   

    return 0;
}

大体上分为两种方式:

1、insert    2、数组下表操作

区别:

当插入的key不存在时,没有区别

当插入的key已经存在时,insert会返回失败,其实insert是有返回值的,std::pair<map<int, string>::iterator, bool> insert_result;它的第一个变量返回的是一个map的迭代器,如果插入成功的话insert_result.second应该是true的,否则为false。

而数组下标操作则是直接用当前值覆盖掉之前旧值,没有操作失败的问题。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值