关联容器之map

  • 头文件

<map>

  • 声明

(1)    

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

(2)    (since C++17)

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>>>
}

  • 描述

std::map是一种有序的关联容器,它包含有“ key-value”对,每个对都有唯一的key。通过使用比较函数Compare来进行排序。搜素、删除和插入操作都是对数复杂度的。它的内部实现是使用了红-黑树。两个对象a和b,如果!comp(a, b) && !comp(b, a)成立,则认为它们是等价的。

std::map meets the requirements of Container, AllocatorAwareContainer, AssociativeContainer and ReversibleContainer.

  • 成员类型
类型定义
key_typeKey
mapped_typeT
value_type std::pair<const Key, T>
size_typeUnsigned integer type (usually std::size_t)
difference_typeSigned integer type (usually std::ptrdiff_t)
key_compareCompare
value_compareCompare
allocator_typeAllocator
referenceAllocator::reference    (until C++11)    value_type&    (since C++11) 
const_referenceAllocator::const_reference    (until C++11)    const value_type&    (since C++11) 
pointer    Allocator::pointer    (until C++11)    std::allocator_traits<Allocator>::pointer    (since C++11) 
const_pointer  Allocator::const_pointer    (until C++11)    std::allocator_traits<Allocator>::const_pointer    (since C++11) 
iterator  LegacyBidirectionalIterator
const_iterator Constant LegacyBidirectionalIterator
reverse_iterator std::reverse_iterator<iterator>
const_reverse_iteratorstd::reverse_iterator<const_iterator>
node_type(since C++17)   a specialization of node handle representing a container node
insert_return_type(since C++17)

 type describing the result of inserting a node_type, a specialization of
template <class Iter, class NodeType> struct /*unspecified*/ {
    Iter     position;
    bool     inserted;
    NodeType node;
};

instantiated with template arguments iterator and node_type.

  • 成员类
value_comparecompares objects of type value_type
(class)
  • 成员访问
at

(1)    (since C++11)

T& at( const Key& key );
(2)    (since C++11)
const T& at( const Key& key ) const;

(C++11)
 access specified element with bounds checking
(public member function)
operator[]

(1) 

T& operator[]( const Key& key );
 (2)    (since C++11)
T& operator[]( Key&& key );

access or insert specified element
(public member function)
  • 迭代器
begin
cbegin
(C++11)
returns an iterator to the beginning
(public member function)
end
cend
(C++11)
returns an iterator to the end
(public member function)
rbegin
crbegin
(C++11)
returns a reverse iterator to the beginning
(public member function)
rend
crend
(C++11)
returns a reverse iterator to the end
(public member function)
  • 指标
emptychecks whether the container is empty
(public member function)
sizereturns the number of elements
(public member function)
max_sizereturns the maximum possible number of elements
(public member function)
  • 修改
clearvoid clear();(until C++11)
void clear() noexcept;(since C++11)
clears the contents
(public member function)
insert

(1)
std::pair<iterator,bool> insert( const value_type& value );
(2)    (since C++11)
template< class P >
std::pair<iterator,bool> insert( P&& value );
(3)    (since C++17)
std::pair<iterator,bool> insert( value_type&& value );

(4)    
(until C++11)iterator insert( iterator hint, const value_type& value );
(since C++11)iterator insert( const_iterator hint, const value_type& value );
(5)    (since C++11)
template< class P >
iterator insert( const_iterator hint, P&& value );
(6)    (since C++17)
iterator insert( const_iterator hint, value_type&& value );
(7)
template< class InputIt >
void insert( InputIt first, InputIt last );
(8)    (since C++11)    
void insert( std::initializer_list<value_type> ilist );
(9)    (since C++17)
insert_return_type insert(node_type&& nh);
(10)    (since C++17)
iterator insert(const_iterator hint, node_type&& nh);

inserts elements or nodes (since C++17)
(public member function)
insert_or_assign(1)    (since C++17) 
template <class M>pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj);
(2)    (since C++17)
template <class M>pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj);
(3)    (since C++17)
template <class M>iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj);
(4)    (since C++17)
template <class M>iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj);
(C++17)inserts an element or assigns to the current element if the key already exists
(public member function)
emplacetemplate< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );
(since C++11)
(C++11)constructs element in-place
(public member function)
emplace_hinttemplate <class... Args>iterator emplace_hint( const_iterator hint, Args&&... args );
(since C++11)
(C++11)constructs elements in-place using a hint
(public member function)
try_emplace(1)    (since C++17)
template <class... Args>pair<iterator, bool> try_emplace(const key_type& k, Args&&... args);
(2)    (since C++17)
template <class... Args>pair<iterator, bool> try_emplace(key_type&& k, Args&&... args);
(3)    (since C++17)
template <class... Args>iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args);
(4)    (since C++17)
template <class... Args>iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args);
(C++17)inserts in-place if the key does not exist, does nothing if the key exists
(public member function)
erase(1)    
(until C++11)void erase( iterator pos );
(since C++11)iterator erase( const_iterator pos );
(since C++17)iterator erase( iterator pos );
(2)    
(until C++11)void erase( iterator first, iterator last );
(since C++11)iterator erase( const_iterator first, const_iterator last );
(3)
size_type erase( const key_type& key );
erases elements
(public member function)
swapvoid swap( map& other );
(until C++17)
void swap( map& other ) noexcept(/* see below */);
(since C++17)
swaps the contents
(public member function)
extract(1)    (since C++17)
node_type extract( const_iterator position );
(2)    (since C++17)
node_type extract( const key_type& x );
(C++17)extracts nodes from the container
(public member function)
merge(1)    (since C++17)
template<class C2>void merge(std::map<Key, T, C2, Allocator>& source);
(2)    (since C++17)
template<class C2>void merge(std::map<Key, T, C2, Allocator>&& source);
(3)    (since C++17)
template<class C2>void merge(std::multimap<Key, T, C2, Allocator>& source);
(4)    (since C++17)
template<class C2>void merge(std::multimap<Key, T, C2, Allocator>&& source);
(C++17)splices nodes from another container
(public member function)
  • 查找
count(1)size_type count( const Key& key ) const;
(2)(since C++14)template< class K > size_type count( const K& x ) const;
returns the number of elements matching specific key
(public member function)
find(1)iterator find( const Key& key );
(2)const_iterator find( const Key& key ) const;
(3)(since C++14)template< class K > iterator find( const K& x );
(4)(since C++14)template< class K > const_iterator find( const K& x ) const;
finds element with specific key
(public member function)
contains(1)(since C++20)bool contains( const Key& key ) const;
(2)(since C++20)template< class K > bool contains( const K& x ) const;
(C++20)
checks if the container contains element with specific key
(public member function)
equal_range(1)std::pair<iterator,iterator>equal_range( const Key& key );    
(2)std::pair<const_iterator,const_iterator> equal_range( const Key& key ) const;
(3)(since C++14)template< class K >std::pair<iterator,iterator> equal_range( const K& x );
(4)(since C++14)template< class K >std::pair<const_iterator,const_iterator> equal_range( const K& x ) const;
Returns a range containing all elements with the given key in the container. The range is defined by two iterators, one pointing to the first element that is not less than key and another pointing to the first element greater than key. Alternatively, the first iterator may be obtained with lower_bound(), and the second with upper_bound().
lower_bound(1)
iterator lower_bound( const Key& key );
const_iterator lower_bound( const Key& key ) const;
(2)
(since C++14)template< class K >iterator lower_bound(const K& x);
(since C++14)template< class K >const_iterator lower_bound(const K& x) const;
returns an iterator to the first element not less than the given key
(public member function)
upper_bound(1)
iterator upper_bound( const Key& key );
const_iterator upper_bound( const Key& key ) const;
(2)    
(since C++14)template< class K >iterator upper_bound( const K& x );
(since C++14)template< class K >const_iterator upper_bound( const K& x ) const;
returns an iterator to the first element greater than the given key
(public member function)
  • 观测器
key_compkey_compare key_comp() const;returns the function that compares keys
(public member function)
value_compstd::set::value_compare value_comp() const;returns the function that compares keys in objects of type value_type
(public member function)
  • 举例

#include <cstddef>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
 
using namespace std::literals;
 
template<typename It> 
void printInsertionStatus(It it, bool success)
{
    std::cout << "Insertion of " << it->first << (success ? " succeeded\n" : " failed\n");
}
 
int main()
{
    std::map<std::string, float> karasunoPlayerHeights;
 
    // Overload 3: insert from rvalue reference
    const auto result = karasunoPlayerHeights.insert({"Hinata"s, 162.8});
    printInsertionStatus(result.first, result.second);
 
    {   
        // Overload 1: insert from lvalue reference
        auto res1 = karasunoPlayerHeights.insert(*result.first);
        printInsertionStatus(res1.first, res1.second);
    }   
    {   
        // Overload 2: insert via forwarding to emplace
        auto res2 = karasunoPlayerHeights.insert({"Kageyama", 180.6});
        printInsertionStatus(res2.first, res2.second);
    }   
 
    {   
        // Overload 6: insert from rvalue reference with positional hint
        const std::size_t n = karasunoPlayerHeights.size();

        const auto it = karasunoPlayerHeights.insert(result.first, {"Azumane"s, 184.7});
        printInsertionStatus(it, karasunoPlayerHeights.size() != n); 
    }   

    {   
        // Overload 4: insert from lvalue reference with positional hint
        const std::size_t n = karasunoPlayerHeights.size();
        const auto it = karasunoPlayerHeights.insert(result.first, *result.first);
        printInsertionStatus(it, karasunoPlayerHeights.size() != n); 
    }
    {
        // Overload 5: insert via forwarding to emplace with positional hint
        const std::size_t n = karasunoPlayerHeights.size();
        const auto it = karasunoPlayerHeights.insert(result.first, {"Tsukishima", 188.3});
        printInsertionStatus(it, karasunoPlayerHeights.size() != n);
    }

    std::map<std::string, float> playerHeights;

    // Overload 7: insert from iterator range
    playerHeights.insert(std::begin(karasunoPlayerHeights), std::end(karasunoPlayerHeights));

    // Overload 8: insert from initializer_list
    playerHeights.insert({{"Kozume"s, 169.2}, {"Kuroo", 187.7}});

    // Print resulting map
    std::cout << std::left << '\n';
    for (const auto& tmp : playerHeights)
        std::cout << std::setw(10) << tmp.first << " | " << tmp.second << "cm\n";
}

  output:

./map.out 
Insertion of Hinata succeeded
Insertion of Hinata failed
Insertion of Kageyama succeeded
Insertion of Azumane succeeded
Insertion of Hinata failed
Insertion of Tsukishima succeeded

Azumane    | 184.7cm
Hinata     | 162.8cm
Kageyama   | 180.6cm
Kozume     | 169.2cm
Kuroo      | 187.7cm
Tsukishima | 188.3cm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值