c++ 11标准模板(STL) std::map(八)

定义于头文件<map>

template<

    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >

> class map;
(1)
namespace pmr {

    template <class Key, class T, class Compare = std::less<Key>>
    using map = std::map<Key, T, Compare,
                         std::pmr::polymorphic_allocator<std::pair<const Key,T>>>

}
(2) (C++17 起)

 std::map 是有序键值对容器,它的元素的键是唯一的。用比较函数 Compare 排序键。搜索、移除和插入操作拥有对数复杂度。 map 通常实现为红黑树

在每个标准库使用比较 (Compare) 概念的位置,以等价关系检验唯一性。不精确而言,若二个对象 ab 互相比较不小于对方 : !comp(a, b) && !comp(b, a) ,则认为它们等价(非唯一)。

std::map 满足容器 (Container) 、具分配器容器 (AllocatorAwareContainer) 、关联容器 (AssociativeContainer) 和可逆容器 (ReversibleContainer) 的要求。

修改器

原位构造元素

std::map<Key,T,Compare,Allocator>::emplace

template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );

(C++11 起)

 若容器中无拥有该关键的元素,则插入以给定的 args 原位构造的新元素到容器。

细心地使用 emplace 允许在构造新元素的同时避免不必要的复制或移动操作。 准确地以与提供给 emplace 者相同的参数,通过 std::forward<Args>(args)... 转发调用新元素(即 std::pair<const Key, T> )的构造函数。 即使容器中已有拥有该关键的元素,也可能构造元素,该情况下新构造的元素将被立即销毁。

没有迭代器或引用被非法化。

参数

args - 要转发给元素构造函数的参数

返回值

返回由指向被插入元素,或若不发生插入则为既存元素的迭代器,和指代插入是否发生的 bool (若发生插入则为 true ,否则为 false )。

异常

若任何操作抛出异常,则此函数无效果。

复杂度

与容器大小成对数。

使用提示原位构造元素

std::map<Key,T,Compare,Allocator>::emplace_hint

template <class... Args>
iterator emplace_hint( const_iterator hint, Args&&... args );

(C++11 起)

 插入元素到尽可能靠近正好在 hint 之前的位置。原位构造元素,即不进行复制或移动操作。

准确地与提供给函数的参数相同者,再以 std::forward<Args>(args)... 转发调用元素类型( value_type ,即 std::pair<const Key, T> )的构造函数。

没有迭代器或引用被非法化。

参数

hint - 指向将插入新元素到其前的位置的迭代器
args - 转发给元素构造函数的参数

返回值

返回指向新插入元素的迭代器。

若因为元素已存在而失败,则返回指向拥有等价关键的既存元素的迭代器。

异常

若任何操作抛出异常,则此函数无效果(强异常保证)。

复杂度

通常与容器大小成对数,但若新元素被插入到恰于 hint 前则为均摊常数。

清除内容

std::map<Key,T,Compare,Allocator>::clear

void clear();

(C++11 前)

void clear() noexcept;

(C++11 起)

 从容器擦除所有元素。此调用后 size() 返回零。

非法化任何指代所含元素的引用、指针或迭代器。任何尾后迭代器保持合法。

参数

(无)

返回值

(无)

复杂度

与容器大小,即元素数成线性。

擦除元素

std::map<Key,T,Compare,Allocator>::erase

void erase( iterator pos );

(1) (C++11 前)

iterator erase( const_iterator pos );

(C++11 起)

iterator erase( iterator pos );

(C++17 起)

void erase( iterator first, iterator last );

(2) (C++11 前)

iterator erase( const_iterator first, const_iterator last );

(C++11 起)

size_type erase( const key_type& key );

(3)

从容器移除指定的元素。

1) 移除位于 pos 的元素。

2) 移除范围 [first; last) 中的元素,它必须是 *this 中的合法范围。

3) 移除关键等于 key 的元素(若存在一个)。

指向被擦除元素的引用和迭代器被非法化。其他引用和迭代器不受影响。

迭代器 pos 必须合法且可解引用。从而 end() 迭代器(合法,但不可解引用)不能用作 pos 所用的值。

参数

pos - 指向要移除的元素的迭代器
first, last - 要移除的元素范围
key - 要移除的元素关键值

返回值

1-2) 后随最后被移除的元素的迭代器。

3) 被移除的元素数。

异常

1,2) (无)

3) 任何 Compare 对象所抛的异常

复杂度

给定 map 的实例 c

1) 均摊常数

2) log(c.size()) + std::distance(first, last)

3) log(c.size()) + c.count(k)

交换内容

std::map<Key,T,Compare,Allocator>::swap

void swap( map& other );

(C++17 前)

void swap( map& other ) noexcept(/* see below */);

(C++17 起)

 将内容与 other 的交换。不在单个元素上调用任何移动、复制或交换操作。

所有迭代器和引用保持合法。尾后迭代器被非法化。

Pred 对象必须可交换 (Swappable) ,并用非成员 swap 的非限定调用交换它们。

若 std::allocator_traits<allocator_type>::propagate_on_container_swap::value 为 true ,则用非成员 swap 的非限定调用交换分配器。否则,不交换它们(且若 get_allocator() != other.get_allocator() ,则行为未定义)。

(C++11 起)

参数

other - 要与之交换内容的容器

返回值

(无)

异常

任何 Compare 对象交换所抛的异常。

(C++17 前)
noexcept 规定:  

noexcept(std::allocator_traits<Allocator>::is_always_equal::value
&& std::is_nothrow_swappable<Compare>::value)

(C++17 起)

复杂度

常数。

调用示例

#include <iostream>
#include <forward_list>
#include <string>
#include <iterator>
#include <algorithm>
#include <functional>
#include <map>
#include <time.h>

using namespace std;

struct Cell
{
    int x;
    int y;

    Cell() = default;
    Cell(int a, int b): x(a), y(b) {}

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator +(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator *(const Cell &cell)
    {
        x *= cell.x;
        y *= cell.y;
        return *this;
    }

    Cell &operator ++()
    {
        x += 1;
        y += 1;
        return *this;
    }


    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }

    bool operator >(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y > cell.y;
        }
        else
        {
            return x > cell.x;
        }
    }

    bool operator ==(const Cell &cell) const
    {
        return x == cell.x && y == cell.y;
    }
};

struct myCompare
{
    bool operator()(const int &a, const int &b)
    {
        return a < b;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

std::ostream &operator<<(std::ostream &os, const std::pair<const int, Cell> &pCell)
{
    os << pCell.first << "-" << pCell.second;
    return os;
}

int main()
{
    auto genKey = []()
    {
        return std::rand() % 10 + 100;
    };

    auto generate = []()
    {
        int n = std::rand() % 10 + 100;
        Cell cell{n, n};
        return cell;
    };

    std::map<int, Cell> map1;
    for (size_t index = 0; index < 5; index++)
    {
        //插入以给定的 args 原位构造的新元素到容器。
        map1.emplace(genKey(), generate());
        std::cout << "map1:    ";
        std::copy(map1.begin(), map1.end(),
                  std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
        std::cout << std::endl;
    }
    std::cout << std::endl;

    std::map<int, Cell> map2;
    for (size_t index = 0; index < 5; index++)
    {
        //插入新元素到尽可能接近恰在 hint 前的呆滞。原位构造元素,即不进行复制或移动操作。
        map2.emplace_hint(map2.begin(), genKey(), generate());
        std::cout << "map2:    ";
        std::copy(map2.begin(), map2.end(),
                  std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
        std::cout << std::endl;
    }
    std::cout << std::endl;

    std::cout << "after swap" << std::endl;
    //将内容与 other 的交换。不在单个元素上调用任何移动、复制或交换操作。
    map1.swap(map2);
    std::cout << "map1:    ";
    std::copy(map1.begin(), map1.end(),
              std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
    std::cout << std::endl;

    std::cout << "map2:    ";
    std::copy(map2.begin(), map2.end(),
              std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;


    //从容器擦除所有元素。此调用后 size() 返回零。
    map1.clear();
    std::cout << "map1 is empty:   " << map1.empty() << std::endl;
    map2.clear();
    std::cout << "map2 is empty:   " << map2.empty() << std::endl;
    std::cout << std::endl;


    std::map<int, Cell> map3({
   
   {genKey(), generate()}, {genKey(), generate()},
        {genKey(), generate()}, {genKey(), generate()}, {genKey(), generate()}});
    //从容器移除指定的元素。1) 移除位于 pos 的元素。
    std::cout << "map3:    ";
    std::copy(map3.begin(), map3.end(),
              std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
    std::cout << std::endl;
    map3.erase(map3.begin());
    std::cout << "map3:    ";
    std::copy(map3.begin(), map3.end(),
              std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
    std::cout << std::endl;

    //从容器移除指定的元素。2) 移除范围 [first; last) 中的元素,它必须是 *this 中的合法范围。
    std::map<int, Cell>::iterator bit = map3.begin();
    std::advance(bit, 1);
    std::map<int, Cell>::iterator ait = bit;
    std::advance(ait, 2);
    map3.erase(bit, ait);
    std::cout << "map3:    ";
    std::copy(map3.begin(), map3.end(),
              std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
    std::cout << std::endl;


    map3.insert({
   
   {genKey(), generate()}, {genKey(), generate()}, {genKey(), generate()}});
    //从容器移除指定的元素。3) 移除关键等于 key 的所有元素。
    std::cout << "map3:    ";
    std::copy(map3.begin(), map3.end(),
              std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
    std::cout << std::endl;
    bit = map3.begin();
    std::advance(bit, 3);
    map3.erase(bit->first);
    std::cout << "map3:    ";
    std::copy(map3.begin(), map3.end(),
              std::ostream_iterator<std::pair<const int, Cell>>(std::cout, " "));
    std::cout << std::endl;
    return 0;
}

输出

猜你喜欢

转载自blog.csdn.net/qq_40788199/article/details/130911397