【STL】 map

1、说明:系统根据C++ Reference学习下STL--> Map

2、Map:Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order. 就是说一个key(关键)值映射一个mapped(映射)值,并且按照欧一定的顺序排列。

(1) key value标记一个一个元素,mapped value通常用来key value对应的内容

(2) Key value和Mapped Value的类型可以不同,一般由

typedef pair<const Key, T> value_type来绑定。

3、Map的基本成员函数

(1) map::at  --> Returns a reference to the mapped value of the element identified with key k

    map<string,int> mymap = {
        {"alpha", 0},
        {"beta", 0},
        {"gamma", 0}};


    mymap.at("alpha") = 10;
    mymap.at("beta") = 20;
    mymap.at("gamma") = 30;

    for(auto &x: mymap){
        cout << x.first << ": " << x.second << endl;
    }

(2)map::begin  --> Returns an iterator referring to the first element in the map container.

    map<char, int> mymap;
    map<char, int>::iterator it;

    mymap['b'] = 100;
    mymap['a'] = 200;
    mymap['c'] = 300;

    for(map<char, int>::iterator it = mymap.begin(); it != mymap.end(); it ++)
    {
        cout << it->first << " => " << it->second << endl;
    }

(3) map::cbegin  -->  Returns a  const_iterator  pointing to the first element in the container.

    map<char, int> mymap;

    mymap['b'] = 100;
    mymap['a'] = 200;
    mymap['c'] = 300;

    cout << "mymap contains:\n";
    for(auto it = mymap.cbegin(); it != mymap.cend(); it ++)
    {
        cout << "[" << (*it).first << ": " << (*it).second << "]\n";
    }

     (4)map::clear  --> Removes all elements from the map container (which are destroyed), leaving the container with a size of 0.

       (5)map::count  --> Searches the container for elements with a key equivalent to k and returns the number of matches.  Map中的所有element都是唯一的。

    map<char, int> mymap;
    char c;

    mymap['a'] = 101;
    mymap['b'] = 202;
    mymap['f'] = 303;

    for(c = 'a'; c < 'h'; c ++)
    {
        cout << c;
        if(mymap.count(c) > 0)
            cout << " is an element of mymap.\n";
        else cout << " is not an element of mymap.\n";
    }
      (6)map::crbegin  --> const_reverse_iterator to the reverse beginning of the sequence.

和cbegin的调用是一致的。

     (7)map::emplace  --> Inserts a new element in the map if its key is unique. This new element is constructed in place using args as the arguments for the construction of a value_type (which is an object of a pair type).  如果键值是唯一的,则插入成功。如果插入成功,则会依照原有的顺序插入到map中

    map<char, int> mymap;
    mymap.emplace('x', 100);
    mymap.emplace('y', 200);
    mymap.emplace('z', 300);

    cout << "mymap contains:\n";
    for(auto &x: mymap){
        cout << "[" << x.first << ", " << x.second << "]\n";
    }

         (8)map::emplace_hint   --> Inserts a new element in the map if its key is unique, with a hint on the insertion position. This new element is constructed in place using args as the arguments for the construction of a value_type (which is an object of a pairtype).

    map<char, int> mymap;
    auto it = mymap.end();

    it = mymap.emplace_hint(it, 'b', 10);
    mymap.emplace_hint(it, 'a', 12);
    mymap.emplace_hint(mymap.end(), 'c', 14);

    cout << "mymap contains: ";
    for(auto &x: mymap)
        cout << "[" << x.first << ", " << x.second << endl;
       (9)map::empty  -->  Returns whether the  map  container is empty (i.e. whether its  size  is  0 ).


       (10)map::equal_range  --> Returns the bounds of a range that includes all the elements in the container which have a key equivalent to k.

    map<char, int> mymap;
    mymap['a'] = 10;
    mymap['b'] = 20;
    mymap['c'] = 30;

    pair<map<char, int>::iterator, map<char, int>::iterator> ret;
    ret = mymap.equal_range('a');

    cout << "lower bound points to: ";
    cout << ret.first->first << " => " << ret.first->second << endl;
    cout << "upper bound points to: ";
    cout << ret.second->first << " => " << ret.second->second << endl;
       (11)map::erase  --> Removes from the map container either a single element or a range of elements ([first,last)).

    map<char, int> mymap;
    map<char, int>::iterator it;

    mymap['a'] = 10;
    mymap['b'] = 20;
    mymap['c'] = 30;
    mymap['d'] = 40;
    mymap['e'] = 50;
    mymap['f'] = 60;

    it = mymap.find('b');
    mymap.erase(it);        //erasing by iterator, erase b

    mymap.erase('c') ;       //erasing by key, erase c

    it = mymap.find('e');
    mymap.erase(it, mymap.end()) ;  //erasing by range, erase e, f

    //输出a d
    for(it = mymap.begin(); it != mymap.end(); ++ it)
        cout << it->first << " => " << it->second << endl;
     (12)map::find  --> Searches the container for an element with a key equivalent to k and returns an iterator to it if found, otherwise it returns an iterator to map::end.

    std::map<char,int> mymap;
    std::map<char,int>::iterator it;

    mymap['a']=50;
    mymap['b']=100;
    mymap['c']=150;
    mymap['d']=200;

    it=mymap.find('b');
    mymap.erase (it);
    mymap.erase (mymap.find('d'));

    // print content:
    std::cout << "elements in mymap:" << '\n';
    std::cout << "a => " << mymap.find('a')->second << '\n';
    std::cout << "c => " << mymap.find('c')->second << '\n';

      (13)map::get_allocate  --> Returns a copy of the allocator object associated with the map.

    int psize;
    map<char, int> mymap;
    pair<const char, int> *p;

    //allocate an array of 5 elements using mymap's allocater.
    p = mymap.get_allocator().allocate(5);

    //assign some values to array
    psize = sizeof(map <char, int>::value_type) * 5;
    cout << "the allocated array has a size of " << psize << " bytes\n";
    mymap.get_allocator().deallocate(p, 5);

      (14)map::insert  --> Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted.  插入时会检查是否已经存在和当前键值一样的元素。

    map<char, int> mymap;

    //first insert function version(single parameter)
    mymap.insert(pair<char, int>('a', 200));
    mymap.insert(pair<char, int>('z', 200));

    pair<map<char, int>::iterator, bool> ret;

    ret = mymap.insert(pair<char, int>('z', 500));
    if(ret.second == false){
        cout << "element '" << ret.first->first << "' already exists";
        cout << " with a value of " << ret.first->second << endl;
    }

    //second insert function version(with hint position)
    map<char, int>::iterator it = mymap.begin();
    mymap.insert(it, pair<char, int>('b', 300));
    mymap.insert(it, pair<char, int>('c', 400));

    //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 << endl;

    cout << "anothermap contains:\n";
    for(it = anothermap.begin(); it != anothermap.end(); ++ it)
        cout << it->first << " => " << it->second << endl;

    (15)map::key_comp  --> Returns a copy of the comparison object used by the container to compare keys.

    map<char, int> mymap;

    map<char, int>::key_compare mycomp = mymap.key_comp();
    mymap['b'] = 400;
    mymap['e'] = 500;
    mymap['f'] = 300;
    mymap['a'] = 100;

    cout << "mymap contains:\n";
    //key value of last element
    char highest = mymap.rbegin()->first;

    map<char, int>::iterator it = mymap.begin();
    do{
        cout << it->first << " => " << it->second << endl;
    }while(mycomp((*it ++).first, highest));

    cout << endl;


     (16)map::lower_bound  -> Returns an iterator pointing to the first element in the container whose key is not considered to go before k (i.e., either it is equivalent or goes after).  he mapcontains an element with a key equivalent to k: In this case, lower_bound returns an iterator pointing to that element, whereas upper_bound returns an iterator pointing to the next element.

    map<char, int> mymap;
    map<char, int>::iterator itlow, itup;

    mymap['a'] = 20;
    mymap['b'] = 40;
    mymap['c'] = 60;
    mymap['d'] = 80;
    mymap['e'] = 100;

    //itlow points to b
    itlow = mymap.lower_bound('a');
    //itup points to e(not 'd')
    itup = mymap.upper_bound('d');

    //erase [itlow, itup)
    mymap.erase(itlow, itup);

    for(map<char, int>::iterator it = mymap.begin(); it != mymap.end(); ++ it)
    {
        cout << it->first << " => " << it->second << endl;
    }
     (17)map::max_size  --> Returns the maximum number of elements that the map container can hold.
    map<int, int> mymap;

    cout << mymap.max_size() << endl;
    if(mymap.max_size() > 1000){
        for(int i = 0; i < 1000; i ++)
            mymap[i] = 0;
        cout << "The map contains 1000 elements" << endl;;
    }
    else cout << "The map could not hold 1000 elements." << endl;
   

   (18)map::operator=  --> Assigns new contents to the container, replacing its current content.

    map<char, int> first;
    map<char, int> second;

    first['x'] = 8;
    first['y'] = 16;
    first['z'] = 32;

    second = first;
    second.insert(pair<char, int>('a', 100));
    first = second;

    cout << "Size of first: " << first.size() << endl;
    cout << "Size of second: " << second.size() << endl;

    first = map<char, int>();
    cout << "Size of first: " << first.size() << endl;
    cout << "Size of second: " << second.size() << endl;


    (19)map::operator[]  -->  A reference to the mapped value of the element with a key value equivalent to  k .

    map<char, string> mymap;

    mymap['a'] = "an element";
    mymap['b'] = "another elment";
    mymap['c'] = mymap['b'];

    cout << "mymap['a'] is " << mymap['a'] << endl;
    cout << "mymap['b'] is " << mymap['b'] << endl;
    cout << "mymap['c'] is " << mymap['c'] << endl;

    cout << "mymap now contains " << mymap.size() << endl;

    (20)map::rbegin  -->  Returns a  reverse iterator  pointing to the last element in the container (i.e., its  reverse beginning ).

    map<char, int> mymap;

    mymap['x'] = 100;
    mymap['y'] = 200;
    mymap['z'] = 300;

    map<char, int>::reverse_iterator rit;
    for(rit=mymap.rbegin(); rit != mymap.rend(); ++rit){
        cout << rit->first << " => " << rit->second << endl;
    }


    (21)map::size  ->  Returns the number of elements in the  map  container.

  

    (22)map::value_comp  --> Returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second.


    (23)map::swap  --> Exchanges the content of the container by the content of x, which is another map of the same type. Sizes may differ.  需要是同种类型的

    map<char, int> foo, bar;

    foo['x'] = 100;
    foo['y'] = 200;

    bar['a'] = 11;
    bar['b'] = 22;
    bar['c'] = 33;

    foo.swap(bar);

    cout << "foo contains: \n";
    for(map<char, int>::iterator it = foo.begin(); it != foo.end(); ++it)
        cout << it->first << " => " << it->second << endl;

    cout << "bar contains: \n";
    for(map<char, int>::iterator it = bar.begin(); it != bar.end(); ++it)
        cout << it->first << " => " << it->second << endl;













03-23
<think>好的,我现在需要回答用户关于C++ STLmap的用法和相关示例的问题。首先,用户提到了引用[1]和[2],其中引用[1]讨论了泛型算法和自定义比较函数的重要性,引用[2]提到了map的find()方法。用户可能想了解map的基本用法、常见操作以及实际示例。 首先,我应该从map的基本概念开始。map是关联容器,存储键值对,按键排序。需要解释它的模板参数,比如键类型、值类型、比较函数和分配器。然后,常用的成员函数,比如插入、访问元素、查找、删除和遍历。 插入元素可以使用insert()或者operator[]。需要注意的是,当使用operator[]时,如果键不存在,会创建一个新条目,而insert()则不会覆盖已存在的键。这点需要说明清楚。 访问元素方面,operator[]和at()的区别在于,at()在键不存在时会抛出异常,而operator[]会创建。这点需要强调,避免用户在使用时出现未预期的行为。 查找元素主要用find()方法,返回迭代器。如果找不到,返回end()。需要提醒用户检查返回值,避免解引用无效迭代器。 删除元素有erase(),可以通过键或迭代器删除。遍历时通常使用迭代器或者C++11的范围for循环,这时候需要提到如何获取键和值。 接下来是示例代码。应该包括创建map、插入元素、访问、查找、删除和遍历的操作。代码要简洁,注释明确。例如,使用insert插入多个键值对,使用operator[]添加新元素,使用find检查是否存在某个键,并用erase删除元素。 然后,根据用户提供的引用,特别是引用[1],可以提到自定义比较函数。比如,默认是less,但用户可以自定义排序规则,比如按降序排列。给出一个示例,使用greater作为比较函数,并展示如何声明这样的map。 另外,性能方面,map基于红黑树,操作时间复杂度是O(log n),这点需要提及,让用户了解其效率特点。 在生成相关问题的时候,需要考虑用户可能进一步的问题,比如map与unordered_map的区别,如何处理自定义类型作为键,性能优化,插入重复键的处理,以及实际应用场景。这些问题可以帮助用户深入理解map的使用和选择合适的数据结构。 最后,确保所有代码示例符合C++语法,并且解释清晰,避免术语混淆。同时,引用用户提供的参考资料,特别是在提到自定义比较函数时引用[1],以及在讨论find()方法时引用[2]。</think>### C++ STL map 用法详解 `std::map` 是 C++ STL 中的关联容器,以键值对(key-value)形式存储数据,并按键自动排序。以下是其核心用法和示例: --- #### 1. 基本定义与初始化 ```cpp #include <map> #include <string> // 定义键为int,值为string的map,默认按升序排列 std::map<int, std::string> student_map; // 初始化示例 std::map<std::string, int> age_map = { {"Alice", 25}, {"Bob", 30} }; ``` --- #### 2. 插入元素 - **`insert()` 方法** 插入新键值对,若键已存在则不会覆盖: ```cpp student_map.insert(std::make_pair(101, "Tom")); student_map.insert({102, "Jerry"}); // C++11 简化语法 ``` - **`operator[]`** 直接通过键赋值,若键不存在则创建新条目: ```cpp age_map["Charlie"] = 28; // 新增键 age_map["Alice"] = 26; // 覆盖原有值 ``` --- #### 3. 访问元素 - **`operator[]` 与 `at()`** ```cpp std::cout << age_map["Bob"]; // 输出30(若键不存在会创建默认值) std::cout << age_map.at("Bob"); // 输出30(若键不存在抛出std::out_of_range异常) ``` --- #### 4. 查找元素 - **`find()` 方法** 返回指向键的迭代器,若未找到则返回`end()` [^2]: ```cpp auto it = age_map.find("Alice"); if (it != age_map.end()) { std::cout << "Found: " << it->second; // 输出值 } ``` --- #### 5. 删除元素 - **`erase()` 方法** 通过键或迭代器删除: ```cpp age_map.erase("Bob"); // 删除键为"Bob"的条目 auto it = age_map.find("Alice"); if (it != age_map.end()) { age_map.erase(it); // 通过迭代器删除 } ``` --- #### 6. 遍历元素 ```cpp // 使用迭代器遍历 for (auto it = age_map.begin(); it != age_map.end(); ++it) { std::cout << it->first << ": " << it->second << std::endl; } // C++11 范围for循环 for (const auto& pair : age_map) { std::cout << pair.first << ": " << pair.second << std::endl; } ``` --- #### 7. 自定义排序规则 可通过模板参数指定比较函数(如降序排列)[^1]: ```cpp #include <functional> std::map<int, std::string, std::greater<int>> desc_map; desc_map[3] = "Third"; desc_map[1] = "First"; // 遍历顺序为3→1 ``` --- #### 8. 性能特点 - **时间复杂度** 插入、删除、查找均为 $O(\log n)$,基于红黑树实现。 - **适用场景** 需要按键有序访问或频繁查找/更新的场景。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值