map 類別

從每個項目都是資料值與排序鍵組的集合,用於資料儲存和擷取。 索引鍵的值是唯一的,用於自動排序資料。

對應中的項目值可以直接變更。 索引鍵值是常數,無法變更。 相反地,與舊項目相關聯的索引鍵值必須刪除,並插入新項目的新索引鍵值。

語法

template <class Key,
    class Type,
    class Traits = less<Key>,
    class Allocator=allocator<pair <const Key, Type>>>
class map;

參數

Key
要儲存在 中的 map 索引鍵資料類型。

Type
要存放在 map 中的項目資料類型。

Traits
型別,提供函式物件,可比較兩個元素值做為排序索引鍵,以判斷其在 中的 map 相對順序。 這個引數是選用引數,且預設值是二元述詞 less<Key>

在 C++14 中,您可以指定 std::less<> 沒有類型參數的述詞,以啟用異質查閱。 如需詳細資訊,請參閱 關聯容器 中的異質查閱。

Allocator
代表預存配置器物件的類型,封裝有關對應之記憶體配置和解除配置的詳細資訊。 這個引數是選擇性的,而且預設值是 allocator<pair<const Key, Type> >

備註

「C++ 標準程式庫」map 類別是:

  • 可變大小的容器,根據關聯的索引鍵值,有效率地擷取項目值。

  • 可逆轉的,因為它提供雙向的迭代器以存取其項目。

  • 已排序,因為其項目是依據指定的比較函式,由索引鍵值排序。

  • 唯一。 因為其項目都必須具有唯一索引鍵。

  • 一個成對關聯的容器,因為其項目資料值和其索引鍵值是不同的。

  • 類別範本,因為它所提供的功能是泛型且與專案或索引鍵類型無關。 用於項目和索引鍵的資料類型是在類別樣板中指定為參數 (和比較函式與配置器一起指定)。

map 類別所提供的反覆運算器是雙向反覆運算器,但 insertmap 類別成員函式具有採用較弱輸入反覆運算器之範本參數的版本,其功能需求小於雙向反覆運算器類別所保證的版本。 不同的迭代器概念因其功能的修改而有關聯性。 每個迭代器概念有自己的一組需求,因此搭配使用的演算法受那些需求所限制。 輸入迭代器可能已取值來參考某個物件,而且可能會遞增為序列中的下一個迭代器。

建議您根據應用程式所需的搜尋和插入種類,來選擇容器類型。 關聯的容器已針對查閱、插入和移除作業最佳化。 明確支援這些作業的成員函式會在最差的情況下執行這些作業,其與容器中元素數目的對數成正比。 插入項目不會使任何迭代器無效,移除項目則僅會使特別指向被移除項目的迭代器無效。

當關聯值與索引鍵的條件由應用程式滿足時,我們建議您選擇使用對應做為關聯容器。 這種結構的模型是已排序的唯一關鍵字清單,其中關聯的字串值提供定義。 如果單字有多個正確的定義,讓索引鍵不是唯一的,則 multimap 會是您選擇的容器。 如果正是要儲存文字清單,則集合將是適當的容器。 如果允許文字的多個項目,則多重集較為適當。

對應會呼叫 類型的 key_compare 預存函式物件,以排序其控制項的專案。 這個預存物件是藉由呼叫 方法來存取的 key_comp 比較函式。 一般而言,任何兩個指定的元素會比較,以判斷一個是否小於另一個元素,或是否相等。 當比較所有項目,會建立已排序的非對等項目序列。

注意

比較函式是在標準數學概念上產生嚴格弱式順序的二元述詞。 二元述詞 f(x,y) 是有兩個引數物件 x 和 y 以及傳回值 truefalse 的函式物件。 如果二元述詞不具彈性、反對稱和可轉移性,而且如果等價是可轉移的,則對集合施加的排序是嚴格的弱式排序,其中當 f(x,y) 和 f(y,x) 和 f(y,x) 都是時,兩個物件 x 和 y 都是 false 相等的。 如果更強的索引鍵相等條件取代等價條件,順序會變成總計 (也就是所有項目彼此相關的排序),因此相符的索引鍵之間將難以辨別。

在 C++14 中,您可以指定沒有類型參數的 std::less<>std::greater<> 述詞,以啟用異質查閱。 如需詳細資訊,請參閱 關聯容器 中的異質查閱。

成員

建構函式

名稱 描述
map 建構特定大小的清單,或具有特定值之項目的清單,或具有特定 allocator 的清單,或是做為其他對應的複本。

Typedefs

名稱 描述
allocator_type 對應物件之 allocator 類別的 typedef。
const_iterator 可以在 const 中讀取 map 項目的雙向迭代器的 typedef。
const_pointer 在對應中指向 const 項目的指標之 typedef。
const_reference typedef,用於參考 const 儲存在地圖中的專案,以便讀取和執行 const 作業。
const_reverse_iterator 提供雙向迭代器的類型,這個迭代器可以讀取 const 中的任何 map 項目。
difference_type 範圍 (介於迭代器所指的項目) 中對應的項目數量的帶正負號整數 typedef。
iterator 雙向迭代器的 typedef,可以讀取或修改對應中的任何項目。
key_compare 函式物件之 typedef,可比較兩個排序鍵以判斷兩個項目在 map 中的相對順序。
key_type 對應中每個項目所儲存之排序鍵的 typedef。
mapped_type 對應中每個項目所儲存之資料的 typedef。
pointer 在對應中指向 const 項目的指標之 typedef。
reference 對應中預存項目的參考之 typedef。
reverse_iterator 雙向迭代器的 typedef,可以讀取或修改反轉對應中的項目。
size_type 不帶正負號的整數 typedef,表示對應中的項目數。
value_type typedef,表示對應中儲存為項目的物件類型。

成員函式

成員函數 描述
at 尋找具有指定索引鍵值的專案。
begin 傳回指向 map 中的第一個項目的迭代器。
cbegin 傳回常數反覆運算器,指向 中的 map 第一個專案。
cend 傳回常數超出結尾 (past-the-end) 迭代器。
clear 清除 map 的所有項目。
containsC++20 檢查 中是否有具有指定索引鍵 map 的專案。
count 傳回對應中索引鍵符合參數所指定之索引鍵的項目數目。
crbegin 傳回常數反覆運算器,指向反轉 map 中的第一個專案。
crend 傳回常數反覆運算器,指向反轉 map 中最後一個專案之後的位置。
emplace 將就地建構的專案插入 。 map
emplace_hint 使用放置提示,將就地建構的專案插入 中 map
empty 如果 map 是空的,則傳 true 回 。
end 傳回超出結尾 (past-the-end) 迭代器。
equal_range 傳回一對迭代器。 配對中第一個迭代器指向 map 中索引鍵大於指定索引鍵的第一個項目。 配對中第二個迭代器指向 map 中索引鍵等於或大於指定索引鍵的第一個項目。
erase 從對應中的指定位置移除項目或某個項目範圍。
find 傳回反覆運算器,指向中索引鍵等於指定索引鍵的專案 map 位置。
get_allocator 傳回用來建構 allocatormap 物件複本。
insert map 中的指定位置插入項目或某個範圍的項目。
key_comp 傳回用來排序 中 map 索引鍵之比較物件的複本。
lower_bound 將反覆運算器傳回至 中 map 索引鍵值等於或大於指定索引鍵之索引鍵值的第一個專案。
max_size 傳回 map 的最大長度。
rbegin 傳回指向反轉 map 中的第一個項目的迭代器。
rend 傳回反覆運算器,指向反轉 map 中最後一個專案之後的位置。
size 傳回 map 中項目的數目。
swap 交換兩個對應的項目。
upper_bound 將反覆運算器傳回至 中的 map 第一個專案,其索引鍵值大於指定索引鍵的值。
value_comp 擷取 map 中用於排序項目值的比較物件之複本。

操作員

名稱 描述
operator[] 將具有特定索引鍵值的項目插入對應中。
operator= 用另一個對應複本取代對應的項目。

allocator_type

一種類型,代表 map 物件的配置器類別。

typedef Allocator allocator_type;

範例

如需使用 allocator_type 的範例,請參閱 範例 get_allocator

at

尋找具有指定之索引鍵值的項目。

Type& at(const Key& key);

const Type& at(const Key& key) const;

參數

key
要尋找的索引鍵值。

傳回值

所找到項目之資料值的參考。

備註

如果找不到引數索引鍵值,則函式會擲回 Class 類別 out_of_range 的物件。

範例

// map_at.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

typedef std::map<char, int> Mymap;
int main()
    {
    Mymap c1;

    c1.insert(Mymap::value_type('a', 1));
    c1.insert(Mymap::value_type('b', 2));
    c1.insert(Mymap::value_type('c', 3));

// find and show elements
    std::cout << "c1.at('a') == " << c1.at('a') << std::endl;
    std::cout << "c1.at('b') == " << c1.at('b') << std::endl;
    std::cout << "c1.at('c') == " << c1.at('c') << std::endl;

    return (0);
    }

begin

傳回迭代器,為 map 中的第一個項目定址。

const_iterator begin() const;

iterator begin();

傳回值

雙向反覆運算器,定址物件是 中的第一 map 個專案,或位置接替空的對應。

範例

// map_begin.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;

   map <int, int> :: iterator m1_Iter;
   map <int, int> :: const_iterator m1_cIter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 0, 0 ) );
   m1.insert ( Int_Pair ( 1, 1 ) );
   m1.insert ( Int_Pair ( 2, 4 ) );

   m1_cIter = m1.begin ( );
   cout << "The first element of m1 is " << m1_cIter -> first << endl;

   m1_Iter = m1.begin ( );
   m1.erase ( m1_Iter );

   // The following 2 lines would err because the iterator is const
   // m1_cIter = m1.begin ( );
   // m1.erase ( m1_cIter );

   m1_cIter = m1.begin( );
   cout << "The first element of m1 is now " << m1_cIter -> first << endl;
}
The first element of m1 is 0
The first element of m1 is now 1

cbegin

傳回 const 迭代器,為範圍中最後一個項目之外的位置定址。

const_iterator cbegin() const;

傳回值

const 雙向迭代器,定址範圍中的第一個項目,或定址空白範圍結尾 (空白範圍 cbegin() == cend()) 之外的位置。

備註

使用 的 cbegin 傳回值,就無法修改範圍中的專案。

您可以使用此成員函式取代 begin() 成員函式,以確保傳回值是 const_iterator。 一般而言,它會與類型推算關鍵字搭配 auto 使用,如下列範例所示。 在此範例中,請考慮將 Container 視為任何支援 begin()cbegin() 且可修改 (非 const) 的容器類型。

auto i1 = Container.begin();
// i1 is Container<T>::iterator
auto i2 = Container.cbegin();

// i2 is Container<T>::const_iterator

cend

傳回 const 迭代器,為範圍中最後一個項目之外的位置定址。

const_iterator cend() const;

傳回值

指向範圍結尾之外的 const 雙向存取迭代器。

備註

cend 用來測試迭代器是否已超過其範圍結尾。

您可以使用此成員函式取代 end() 成員函式,以確保傳回值是 const_iterator。 一般而言,它會與類型推算關鍵字搭配 auto 使用,如下列範例所示。 在此範例中,請考慮將 Container 視為任何支援 end()cend() 且可修改 (非 const) 的容器類型。

auto i1 = Container.end();
// i1 is Container<T>::iterator
auto i2 = Container.cend();

// i2 is Container<T>::const_iterator

cend 所傳回的值不應該取值。

clear

清除對應的所有項目。

void clear();

範例

下列範例示範如何使用 map::clear 成員函式。

// map_clear.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main()
{
    using namespace std;
    map<int, int> m1;
    map<int, int>::size_type i;
    typedef pair<int, int> Int_Pair;

    m1.insert(Int_Pair(1, 1));
    m1.insert(Int_Pair(2, 4));

    i = m1.size();
    cout << "The size of the map is initially "
         << i << "." << endl;

    m1.clear();
    i = m1.size();
    cout << "The size of the map after clearing is "
         << i << "." << endl;
}
The size of the map is initially 2.
The size of the map after clearing is 0.

const_iterator

提供雙向迭代器的類型,這個迭代器可以讀取 const 中的 map 項目。

typedef implementation-defined const_iterator;

備註

類型 const_iterator 無法用來修改專案的值。

const_iterator由 map 所定義的 指向 屬於 的物件 value_type ,其 pair<constKey, Type> 第一個成員是 元素的索引鍵,而第二個成員是 元素所持有的對應日期。

若要對指向 map 中某個元素的 const_iteratorcIter 進行取值,請使用 -> 運算子。

若要存取專案的索引鍵值,請使用 cIter - >first ,這相當於 (* cIter )。 first.

若要存取專案的對應日期值,請使用 cIter - >second ,這相當於 (* cIter )。 second.

範例

如需使用 const_iterator 的範例,請參閱 範例 begin

const_pointer

提供對應中專案指標 const 的型別。

typedef typename allocator_type::const_pointer const_pointer;

備註

類型 const_pointer 無法用來修改專案的值。

在大部分情況下, iterator 應該使用 來存取對應物件中的專案。

const_reference

型別,提供儲存在對應中之元素的參考 const ,以便讀取和執行 const 作業。

typedef typename allocator_type::const_reference const_reference;

範例

// map_const_ref.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );

   // Declare and initialize a const_reference &Ref1
   // to the key of the first element
   const int &Ref1 = ( m1.begin( ) -> first );

   // The following line would cause an error as the
   // non-const_reference can't be used to access the key
   // int &Ref1 = ( m1.begin( ) -> first );

   cout << "The key of first element in the map is "
        << Ref1 << "." << endl;

   // Declare and initialize a reference &Ref2
   // to the data value of the first element
   int &Ref2 = ( m1.begin( ) -> second );

   cout << "The data value of first element in the map is "
        << Ref2 << "." << endl;
}
The key of first element in the map is 1.
The data value of first element in the map is 10.

const_reverse_iterator

提供雙向迭代器的類型,這個迭代器可以讀取 const 中的任何 map 項目。

typedef std::reverse_iterator<const_iterator> const_reverse_iterator;

備註

類型 const_reverse_iterator 無法修改專案的值,並且用來反向逐一查看對應。

const_reverse_iterator由 map 所定義的 指向 屬於 的物件 value_type ,其 pair<const Key, Type> 第一個成員是 元素的索引鍵,而第二個成員是 元素所持有的對應日期。

若要對指向 map 中某個元素的 const_reverse_iterator crIter 進行取值,請使用 -> 運算子。

若要存取元素的索引鍵值,請使用 crIter - first> ,這相當於 (* crIter )。 first

若要存取專案的對應日期值,請使用 crIter - second> ,這相當於 (* crIter )。 first

範例

如需如何宣告和使用 const_reverse_iterator 的範例 rend ,請參閱範例。

count

傳回對應中索引鍵符合參數指定之索引鍵的項目數。

size_type count(const Key& key) const;

參數

key
要從對應中比對之項目的索引鍵值。

傳回值

如果對應包含排序索引鍵符合參數索引鍵的項目則為 1;如果對應不含具有相符索引鍵的項目則為 0。

備註

成員函式會傳回下列範圍中的元素數目 x

[ lower_bound( key ), upper_bound( key ) )

,其為對應案例中的 0 或 1,且是唯一相關聯的容器。

範例

下列範例示範如何使用 map::count 成員函式。

// map_count.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main()
{
    using namespace std;
    map<int, int> m1;
    map<int, int>::size_type i;
    typedef pair<int, int> Int_Pair;

    m1.insert(Int_Pair(1, 1));
    m1.insert(Int_Pair(2, 1));
    m1.insert(Int_Pair(1, 4));
    m1.insert(Int_Pair(2, 1));

    // Keys must be unique in map, so duplicates are ignored
    i = m1.count(1);
    cout << "The number of elements in m1 with a sort key of 1 is: "
         << i << "." << endl;

    i = m1.count(2);
    cout << "The number of elements in m1 with a sort key of 2 is: "
         << i << "." << endl;

    i = m1.count(3);
    cout << "The number of elements in m1 with a sort key of 3 is: "
         << i << "." << endl;
}
The number of elements in m1 with a sort key of 1 is: 1.
The number of elements in m1 with a sort key of 2 is: 1.
The number of elements in m1 with a sort key of 3 is: 0.

contains

檢查 中是否有具有指定索引鍵 map 的專案。

bool contains(const Key& key) const;
template<class K> bool contains(const K& key) const;

參數

K
索引鍵的類型。

key
要尋找的專案索引鍵值。

傳回值

true 如果在容器中找到專案,則為 ; false 否則。

備註

contains() 是 C++20 的新功能。 若要使用它,請指定 /std:c++20 或更新版本的編譯器選項。

template<class K> bool contains(const K& key) const 只有在透明時 key_compare 才會參與多載解析。 如需詳細資訊,請參閱 關聯容器 中的異質查閱。

範例

// Requires /std:c++20 or /std:c++latest
#include <map>
#include <string>
#include <iostream>
#include <functional>

int main()
{
    std::map<int, bool> m = {{0, true},{1, false}};

    std::cout << std::boolalpha; // so booleans show as 'true' or 'false'
    std::cout << m.contains(1) << '\n';
    std::cout << m.contains(2) << '\n';

    // call template function
    std::map<std::string, int, std::less<>> m2 = {{"ten", 10}, {"twenty", 20}, {"thirty", 30}};
    std::cout << m2.contains("ten");

    return 0;
}
true
false
true

crbegin

傳回常數迭代器,定址對象是反轉 map 中的第一個元素。

const_reverse_iterator crbegin() const;

傳回值

常數反向雙向反覆運算器,定址反 map 轉中的第一個元素,或定址未反 map 轉 中的最後一個專案。

備註

crbegin與 反轉 map 搭配使用,就像 搭配 使用一 mapbegin

使用 的 crbegin 傳回值, map 就無法修改物件

crbegin 可用來向後逐一查看 map

範例

// map_crbegin.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;

   map <int, int> :: const_reverse_iterator m1_crIter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );

   m1_crIter = m1.crbegin( );
   cout << "The first element of the reversed map m1 is "
        << m1_crIter -> first << "." << endl;
}
The first element of the reversed map m1 is 3.

crend

傳回常數迭代器,定址對象是反轉 map 中最後一個元素後面的位置。

const_reverse_iterator crend() const;

傳回值

常數反向雙向反覆運算器,定址物件是反轉中最後一個專案之後的位置(在未反 mapmap 的第一個專案之前的位置)。

備註

crend與反向對應搭配使用,就像 搭配 使用一 mapend

使用 的 crend 傳回值, map 就無法修改 物件。

crend 可以用來測試反轉迭代器是否已到達其 map 的結尾。

crend 所傳回的值不應該取值。

範例

// map_crend.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;

   map <int, int> :: const_reverse_iterator m1_crIter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );

   m1_crIter = m1.crend( );
   m1_crIter--;
   cout << "The last element of the reversed map m1 is "
        << m1_crIter -> first << "." << endl;
}
The last element of the reversed map m1 is 1.

difference_type

一種帶正負號的整數類型,可用來代表範圍 (介於迭代器所指的元素之間) 中 map 的元素數目。

typedef allocator_type::difference_type difference_type;

備註

difference_type 是透過容器的迭代器減去或遞增時會傳回的類型。 difference_type 通常用來代表迭代器 firstlast 之間範圍 [ first, last) 內的元素數目,包括 first 所指的元素以及上限到 last 所指元素 (但不包含此元素) 的元素範圍。

雖然 difference_type 適用于所有符合輸入反覆運算器需求的反覆運算器,其中包含可逆容器所支援的雙向反覆運算器類別,例如 set,但反覆運算器之間的減法僅受隨機存取反覆運算器所提供的隨機存取反覆運算器支援,例如向量。

範例

// map_diff_type.cpp
// compile with: /EHsc
#include <iostream>
#include <map>
#include <algorithm>

int main( )
{
   using namespace std;
   map <int, int> m1;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 3, 20 ) );
   m1.insert ( Int_Pair ( 2, 30 ) );

   map <int, int>::iterator m1_Iter, m1_bIter, m1_eIter;
   m1_bIter = m1.begin( );
   m1_eIter = m1.end( );

   // Count the number of elements in a map
   map <int, int>::difference_type  df_count = 1;
   m1_Iter = m1.begin( );
   while ( m1_Iter != m1_eIter)
   {
      df_count++;
      m1_Iter++;
   }

   cout << "The number of elements in the map m1 is: "
        << df_count << "." << endl;
}
The number of elements in the map m1 is: 4.

emplace

將就地建構 (未執行任何複製或移動作業) 的元素插入到 map 中。

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

參數

args
轉送的引數會建構要插入對應中的專案,除非它已經包含其值相等排序的專案。

傳回值

pair,其 bool 元件是在 true 進行插入時,如果 false 對應已經包含排序中相等值的專案,則為 。 若 bool 元件為 True,傳回值組的迭代器元件會指向最新插入的元素;若 bool 元件為 False,則會指向現有元素。

若要存取 pairpr 的迭代器元件,請使用 pr.first;若要取其值,請使用 *pr.first。 若要存取 bool 元件,請使用 pr.second。 例如,請參閱本文中稍後的範例程式碼。

備註

此函式不會使任何迭代器或參考失效。

在放置期間,如果擲回例外狀況,則不會修改容器的狀態。

value_type專案的 是一對,因此元素的值會是排序的配對,第一個元件等於索引鍵值,而第二個元件等於專案的資料值。

範例

// map_emplace.cpp
// compile with: /EHsc
#include <map>
#include <string>
#include <iostream>

using namespace std;

template <typename M> void print(const M& m) {
    cout << m.size() << " elements: ";

    for (const auto& p : m) {
        cout << "(" << p.first << ", " << p.second << ") ";
    }

    cout << endl;
}

int main()
{
    map<int, string> m1;

    auto ret = m1.emplace(10, "ten");

    if (!ret.second){
        auto pr = *ret.first;
        cout << "Emplace failed, element with key 10 already exists."
            << endl << "  The existing element is (" << pr.first << ", " << pr.second << ")"
            << endl;
        cout << "map not modified" << endl;
    }
    else{
        cout << "map modified, now contains ";
        print(m1);
    }
    cout << endl;

    ret = m1.emplace(10, "one zero");

    if (!ret.second){
        auto pr = *ret.first;
        cout << "Emplace failed, element with key 10 already exists."
            << endl << "  The existing element is (" << pr.first << ", " << pr.second << ")"
            << endl;
    }
    else{
        cout << "map modified, now contains ";
        print(m1);
    }
    cout << endl;
}

emplace_hint

將就地建構 (未執行任何複製或移動作業) 的元素連同位置提示一起插入。

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

參數

args
轉送的引數會建構要插入對應中的專案,除非對應已經包含該元素,或者,更一般地說,除非它已經包含索引鍵相等排序的專案。

where
要開始搜尋正確的插入點的地方。 (如果該點緊 接在何處 ,插入可能會以分攤的常數時間發生,而不是對數時間。

傳回值

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

如果因為元素已經存在而插入失敗,便會傳回指向現有元素及其索引鍵的迭代器。

備註

此函式不會使任何迭代器或參考失效。

在放置期間,如果擲回例外狀況,則不會修改容器的狀態。

value_type專案的 是一對,因此元素的值會是排序的配對,第一個元件等於索引鍵值,而第二個元件等於專案的資料值。

範例

// map_emplace.cpp
// compile with: /EHsc
#include <map>
#include <string>
#include <iostream>

using namespace std;

template <typename M> void print(const M& m) {
    cout << m.size() << " elements: " << endl;

    for (const auto& p : m) {
        cout << "(" << p.first <<  "," << p.second << ") ";
    }

    cout << endl;
}

int main()
{
    map<string, string> m1;

    // Emplace some test data
    m1.emplace("Anna", "Accounting");
    m1.emplace("Bob", "Accounting");
    m1.emplace("Carmine", "Engineering");

    cout << "map starting data: ";
    print(m1);
    cout << endl;

    // Emplace with hint
    // m1.end() should be the "next" element after this emplacement
    m1.emplace_hint(m1.end(), "Doug", "Engineering");

    cout << "map modified, now contains ";
    print(m1);
    cout << endl;
}

empty

測試 map 是否是空的。

bool empty() const;

傳回值

true 如果地圖是空的,則為 ; false 如果地圖是空的,則為 。

範例

// map_empty.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1, m2;

   typedef pair <int, int> Int_Pair;
   m1.insert ( Int_Pair ( 1, 1 ) );

   if ( m1.empty( ) )
      cout << "The map m1 is empty." << endl;
   else
      cout << "The map m1 is not empty." << endl;

   if ( m2.empty( ) )
      cout << "The map m2 is empty." << endl;
   else
      cout << "The map m2 is not empty." << endl;
}
The map m1 is not empty.
The map m2 is empty.

end

傳回超出結尾 (past-the-end) 迭代器。

const_iterator end() const;

iterator end();

傳回值

超出結尾迭代器。 如果 map 是空的,則 map::end() == map::begin()

備註

end 是用來測試反覆運算器是否已通過其地圖的結尾。

end 所傳回的值不應該取值。

如需程式碼範例,請參閱map::find

equal_range

傳回一組反覆運算器,代表 lower_bound 索引鍵和 upper_bound 索引鍵的 。

pair <const_iterator, const_iterator> equal_range (const Key& key) const;

pair <iterator, iterator> equal_range (const Key& key);

參數

key
要與所搜尋之對應中元素的排序鍵比較的引數索引鍵值。

傳回值

若要存取成員函式所傳回之 pr 配對的第一個迭代器,請使用 pr. 首先 ,若要取值下限反覆運算器,請使用 *( prfirst )。 若要存取成員函式所傳回之配對 pr 的第二個迭代器,請使用 pr. 第二 個,若要取值上限反覆運算器,請使用 *( prsecond )。

範例

// map_equal_range.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   typedef map <int, int, less<int> > IntMap;
   IntMap m1;
   map <int, int> :: const_iterator m1_RcIter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );

   pair <IntMap::const_iterator, IntMap::const_iterator> p1, p2;
   p1 = m1.equal_range( 2 );

   cout << "The lower bound of the element with "
        << "a key of 2 in the map m1 is: "
        << p1.first -> second << "." << endl;

   cout << "The upper bound of the element with "
        << "a key of 2 in the map m1 is: "
        << p1.second -> second << "." << endl;

   // Compare the upper_bound called directly
   m1_RcIter = m1.upper_bound( 2 );

   cout << "A direct call of upper_bound( 2 ) gives "
        << m1_RcIter -> second << "," << endl
        << "matching the 2nd element of the pair"
        << " returned by equal_range( 2 )." << endl;

   p2 = m1.equal_range( 4 );

   // If no match is found for the key,
   // both elements of the pair return end( )
   if ( ( p2.first == m1.end( ) ) && ( p2.second == m1.end( ) ) )
      cout << "The map m1 doesn't have an element "
           << "with a key less than 40." << endl;
   else
      cout << "The element of map m1 with a key >= 40 is: "
           << p2.first -> first << "." << endl;
}
The lower bound of the element with a key of 2 in the map m1 is: 20.
The upper bound of the element with a key of 2 in the map m1 is: 30.
A direct call of upper_bound( 2 ) gives 30,
matching the 2nd element of the pair returned by equal_range( 2 ).
The map m1 doesn't have an element with a key less than 40.

erase

從 map 中指定的位置移除某個元素或某個範圍的元素,或移除符合指定索引鍵的元素。

iterator erase(
    const_iterator Where);

iterator erase(
    const_iterator First,
    const_iterator Last);

size_type erase(
    const key_type& Key);

參數

Where
要移除之項目的位置。

First
要移除之第一個項目的位置。

Last
緊接在要移除之最後一個項目後面的位置。

Key
要移除之項目的索引鍵值。

傳回值

針對前兩個成員函式,會傳回雙向迭代器,其中指定任何移除之元素後剩餘的第一個元素,或如果沒有這類元素,則傳回 map 結尾的元素。

針對第三個成員函式,會傳回已從 map 移除的元素數目。

範例

// map_erase.cpp
// compile with: /EHsc
#include <map>
#include <string>
#include <iostream>
#include <iterator> // next() and prev() helper functions
#include <utility>  // make_pair()

using namespace std;

using mymap = map<int, string>;

void printmap(const mymap& m) {
    for (const auto& elem : m) {
        cout << " [" << elem.first << ", " << elem.second << "]";
    }
    cout << endl << "size() == " << m.size() << endl << endl;
}

int main()
{
    mymap m1;

    // Fill in some data to test with, one at a time
    m1.insert(make_pair(1, "A"));
    m1.insert(make_pair(2, "B"));
    m1.insert(make_pair(3, "C"));
    m1.insert(make_pair(4, "D"));
    m1.insert(make_pair(5, "E"));

    cout << "Starting data of map m1 is:" << endl;
    printmap(m1);
    // The 1st member function removes an element at a given position
    m1.erase(next(m1.begin()));
    cout << "After the 2nd element is deleted, the map m1 is:" << endl;
    printmap(m1);

    // Fill in some data to test with, one at a time, using an initializer list
    mymap m2
    {
        { 10, "Bob" },
        { 11, "Rob" },
        { 12, "Robert" },
        { 13, "Bert" },
        { 14, "Bobby" }
    };

    cout << "Starting data of map m2 is:" << endl;
    printmap(m2);
    // The 2nd member function removes elements
    // in the range [First, Last)
    m2.erase(next(m2.begin()), prev(m2.end()));
    cout << "After the middle elements are deleted, the map m2 is:" << endl;
    printmap(m2);

    mymap m3;

    // Fill in some data to test with, one at a time, using emplace
    m3.emplace(1, "red");
    m3.emplace(2, "yellow");
    m3.emplace(3, "blue");
    m3.emplace(4, "green");
    m3.emplace(5, "orange");
    m3.emplace(6, "purple");
    m3.emplace(7, "pink");

    cout << "Starting data of map m3 is:" << endl;
    printmap(m3);
    // The 3rd member function removes elements with a given Key
    mymap::size_type count = m3.erase(2);
    // The 3rd member function also returns the number of elements removed
    cout << "The number of elements removed from m3 is: " << count << "." << endl;
    cout << "After the element with a key of 2 is deleted, the map m3 is:" << endl;
    printmap(m3);
}

find

傳回迭代器,參考對象是 map 中索引鍵等於指定索引鍵的元素位置。

iterator find(const Key& key);

const_iterator find(const Key& key) const;

參數

key
要以所搜尋之 map 中元素的排序鍵比對的索引鍵值。

傳回值

反覆運算器,參考具有指定索引鍵之專案的位置,如果找不到索引鍵相符專案,則為 () 中 mapmap::end() 最後一個專案後置的位置。

備註

成員函式會傳回反覆運算器,其 map 排序索引鍵相當於二元述詞下的引數索引鍵,根據小於可比較性關聯來引發排序。

如果將 的 find 傳回值指派給 const_iterator ,則無法修改 map 物件。 如果 的 find 傳回值指派給 iterator ,則可以修改 map 物件

範例

// compile with: /EHsc /W4 /MTd
#include <map>
#include <iostream>
#include <vector>
#include <string>
#include <utility>  // make_pair()

using namespace std;

template <typename A, typename B> void print_elem(const pair<A, B>& p) {
    cout << "(" << p.first << ", " << p.second << ") ";
}

template <typename T> void print_collection(const T& t) {
    cout << t.size() << " elements: ";

    for (const auto& p : t) {
        print_elem(p);
    }
    cout << endl;
}

template <typename C, class T> void findit(const C& c, T val) {
    cout << "Trying find() on value " << val << endl;
    auto result = c.find(val);
    if (result != c.end()) {
        cout << "Element found: "; print_elem(*result); cout << endl;
    } else {
        cout << "Element not found." << endl;
    }
}

int main()
{
    map<int, string> m1({ { 40, "Zr" }, { 45, "Rh" } });
    cout << "The starting map m1 is (key, value):" << endl;
    print_collection(m1);

    vector<pair<int, string>> v;
    v.push_back(make_pair(43, "Tc"));
    v.push_back(make_pair(41, "Nb"));
    v.push_back(make_pair(46, "Pd"));
    v.push_back(make_pair(42, "Mo"));
    v.push_back(make_pair(44, "Ru"));
    v.push_back(make_pair(44, "Ru")); // attempt a duplicate

    cout << "Inserting the following vector data into m1:" << endl;
    print_collection(v);

    m1.insert(v.begin(), v.end());

    cout << "The modified map m1 is (key, value):" << endl;
    print_collection(m1);
    cout << endl;
    findit(m1, 45);
    findit(m1, 6);
}

get_allocator

傳回一份用來建構 map 的配置器物件複本。

allocator_type get_allocator() const;

傳回值

map 所使用的配置器。

備註

map 類別的配置器會指定此類別管理儲存體的方式。 C++ 標準程式庫容器類別隨附的預設配置器,足以滿足大多數程式設計需求。 撰寫和使用您自己的配置器類別是進階 C++ 主題。

範例

// map_get_allocator.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int>::allocator_type m1_Alloc;
   map <int, int>::allocator_type m2_Alloc;
   map <int, double>::allocator_type m3_Alloc;
   map <int, int>::allocator_type m4_Alloc;

   // The following lines declare objects
   // that use the default allocator.
   map <int, int> m1;
   map <int, int, allocator<int> > m2;
   map <int, double, allocator<double> > m3;

   m1_Alloc = m1.get_allocator( );
   m2_Alloc = m2.get_allocator( );
   m3_Alloc = m3.get_allocator( );

   cout << "The number of integers that can be allocated\n"
        << "before free memory is exhausted: "
        << m2.max_size( ) << ".\n" << endl;

   cout << "The number of doubles that can be allocated\n"
        << "before free memory is exhausted: "
        << m3.max_size( ) <<  ".\n" << endl;

   // The following line creates a map m4
   // with the allocator of map m1.
   map <int, int> m4( less<int>( ), m1_Alloc );

   m4_Alloc = m4.get_allocator( );

   // Two allocators are interchangeable if
   // storage allocated from each can be
   // deallocated with the other
   if( m1_Alloc == m4_Alloc )
   {
      cout << "The allocators are interchangeable." << endl;
   }
   else
   {
      cout << "The allocators are not interchangeable." << endl;
   }
}

insert

將某個項目或項目範圍插入對應中。

// (1) single element
pair<iterator, bool> insert(
    const value_type& Val);

// (2) single element, perfect forwarded
template <class ValTy>
pair<iterator, bool>
insert(
    ValTy&& Val);

// (3) single element with hint
iterator insert(
    const_iterator Where,
    const value_type& Val);

// (4) single element, perfect forwarded, with hint
template <class ValTy>
iterator insert(
    const_iterator Where,
    ValTy&& Val);

// (5) range
template <class InputIterator>
void insert(
    InputIterator First,
    InputIterator Last);

// (6) initializer list
void insert(
    initializer_list<value_type>
IList);

參數

Val
要插入對應的專案值,除非它已經包含索引鍵相等排序的專案。

Where
要開始搜尋正確的插入點的地方。 (若該點緊接於 Where 之前,則可能會在分攤常數時間插入,而不是對數時間)。

ValTy
樣板參數,指定對應可用來建構 的 元素的 value_type 引數類型,並以完美轉送 Val 做為引數。

First
要複製之第一個元素的位置。

Last
要複製之最一個元素後方的位置。

InputIterator
符合輸入反覆運算器 需求的 樣板函式引數,指向可用來建構 value_type 物件之型別的專案。

IList
initializer_list要從中複製專案的 。

傳回值

單一元素成員函式 (1) 和 (2) 會傳回 ,如果已進行插入,則傳回其 bool 元件為 true 的 ,如果對應已經包含索引鍵具有排序中相等值的專案,則傳回 pair false。 若 bool 元件為 True,傳回值組的迭代器元件會指向最新插入的元素;若 bool 元件為 False,則會指向現有元素。

具有提示的單一項目成員函式 (3) 及 (4) 會傳回指向位置的迭代器,該位置是新項目插入對應中的位置,或者,若對等索引鍵已存在,則指向現有項目。

備註

此函式不會使任何迭代器、指標或參考無效。

在只插入一個專案期間,如果擲回例外狀況,則不會修改容器的狀態。 在插入多個元素期間,若擲出例外狀況,則容器會處於未指定但有效的狀態。

若要存取 pairpr 的迭代器元件 (由單一元素成員函式傳回),請使用 pr.first;若要對傳回的 pair 中的迭代器取值,請使用 *pr.first (提供您元素)。 若要存取 bool 元件,請使用 pr.second。 例如,請參閱本文中稍後的範例程式碼。

value_type容器的 是屬於容器的 typedef,而對應 map<K, V>::value_type 則為 pair<const K, V> 。 元素的值是已排序的配對,其中第一個元件等於索引鍵值,而第二個元件等於元素的資料值。

範圍成員函式 (5) 會將項目值的序列插入對應至每個項目的對應,而這些項目是由範圍 [First, Last) 中的迭代器指定;因此不會插入 Last。 容器成員函式 end() 會參考容器中最後一個項目之後的位置。例如陳述式 m.insert(v.begin(), v.end()); 嘗試將 v 的所有項目插入 m。 只會插入具有範圍中唯一值的元素;若重複則會忽略。 若要觀察哪些元素會遭到拒絕,請使用單一元素版本的 insert

初始化運算式清單成員函式 (6) 會使用 initializer_list 將專案複製到對應中。

若要插入就地建構的專案,也就是不會執行任何複製或移動作業,請參閱 map::emplacemap::emplace_hint

範例

// map_insert.cpp
// compile with: /EHsc
#include <map>
#include <iostream>
#include <string>
#include <vector>
#include <utility>  // make_pair()

using namespace std;

template <typename M> void print(const M& m) {
    cout << m.size() << " elements: ";

    for (const auto& p : m) {
        cout << "(" << p.first << ", " << p.second << ") ";
    }

    cout << endl;
}

int main()
{
    // insert single values
    map<int, int> m1;
    // call insert(const value_type&) version
    m1.insert({ 1, 10 });
    // call insert(ValTy&&) version
    m1.insert(make_pair(2, 20));

    cout << "The original key and mapped values of m1 are:" << endl;
    print(m1);

    // intentionally attempt a duplicate, single element
    auto ret = m1.insert(make_pair(1, 111));
    if (!ret.second){
        auto pr = *ret.first;
        cout << "Insert failed, element with key value 1 already exists."
            << endl << "  The existing element is (" << pr.first << ", " << pr.second << ")"
            << endl;
    }
    else{
        cout << "The modified key and mapped values of m1 are:" << endl;
        print(m1);
    }
    cout << endl;

    // single element, with hint
    m1.insert(m1.end(), make_pair(3, 30));
    cout << "The modified key and mapped values of m1 are:" << endl;
    print(m1);
    cout << endl;

    // The templatized version inserting a jumbled range
    map<int, int> m2;
    vector<pair<int, int>> v;
    v.push_back(make_pair(43, 294));
    v.push_back(make_pair(41, 262));
    v.push_back(make_pair(45, 330));
    v.push_back(make_pair(42, 277));
    v.push_back(make_pair(44, 311));

    cout << "Inserting the following vector data into m2:" << endl;
    print(v);

    m2.insert(v.begin(), v.end());

    cout << "The modified key and mapped values of m2 are:" << endl;
    print(m2);
    cout << endl;

    // The templatized versions move-constructing elements
    map<int, string>  m3;
    pair<int, string> ip1(475, "blue"), ip2(510, "green");

    // single element
    m3.insert(move(ip1));
    cout << "After the first move insertion, m3 contains:" << endl;
    print(m3);

    // single element with hint
    m3.insert(m3.end(), move(ip2));
    cout << "After the second move insertion, m3 contains:" << endl;
    print(m3);
    cout << endl;

    map<int, int> m4;
    // Insert the elements from an initializer_list
    m4.insert({ { 4, 44 }, { 2, 22 }, { 3, 33 }, { 1, 11 }, { 5, 55 } });
    cout << "After initializer_list insertion, m4 contains:" << endl;
    print(m4);
    cout << endl;
}

iterator

一種類型,提供可讀取或修改 map 中任何元素的雙向迭代器。

typedef implementation-defined iterator;

備註

由 map 所定義的反覆運算器會指向 屬於 的物件 value_type ,其 pair<const Key, Type> 類型為 的 元素,其第一個成員是元素的索引鍵,而其第二個成員是 元素所持有的對應日期。

若要取值指向對應中元素的反覆運算器反覆運算器 ,請使用 -> 運算子。

若要存取專案的索引鍵值,請使用 Iter->first(*Iter).first 相當於 的 。 若要存取專案的對應日期值,請使用 Iter->second(*Iter).second 相當於 的 。

範例

begin如需如何宣告和使用 iterator 的範例,請參閱 範例。

key_comp

擷取一份用來排序 map 中索引鍵的比較物件複本。

key_compare key_comp() const;

傳回值

傳回 map 用來排序其元素的函式物件。

備註

預存物件會定義成員函式

bool operator(const Key& left, const Key& right);

如果 之前和 在排序次序中不等於 right ,則會傳 trueleft 回 。

範例

// map_key_comp.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;

   map <int, int, less<int> > m1;
   map <int, int, less<int> >::key_compare kc1 = m1.key_comp( ) ;
   bool result1 = kc1( 2, 3 ) ;
   if( result1 == true )
   {
      cout << "kc1( 2,3 ) returns value of true, "
           << "where kc1 is the function object of m1."
           << endl;
   }
   else
   {
      cout << "kc1( 2,3 ) returns value of false "
           << "where kc1 is the function object of m1."
           << endl;
   }

   map <int, int, greater<int> > m2;
   map <int, int, greater<int> >::key_compare kc2 = m2.key_comp( );
   bool result2 = kc2( 2, 3 ) ;
   if( result2 == true )
   {
      cout << "kc2( 2,3 ) returns value of true, "
           << "where kc2 is the function object of m2."
           << endl;
   }
   else
   {
      cout << "kc2( 2,3 ) returns value of false, "
           << "where kc2 is the function object of m2."
           << endl;
   }
}
kc1( 2,3 ) returns value of true, where kc1 is the function object of m1.
kc2( 2,3 ) returns value of false, where kc2 is the function object of m2.

key_compare

類型,提供可以比較兩個排序鍵的函式物件,以判斷兩個項目在 map 中的相對順序。

typedef Traits key_compare;

備註

key_compare 與樣板參數 Traits 同義。

如需 的詳細資訊 Traits ,請參閱 map 類別 主題。

範例

key_comp如需如何宣告和使用 key_compare 的範例,請參閱 範例。

key_type

一種類型,描述儲存在 map 每個元素中的排序鍵。

typedef Key key_type;

備註

key_type 與樣板參數 Key 同義。

如需 的詳細資訊 Key ,請參閱 類別 主題的 map < 備註>一節。

範例

value_type如需如何宣告和使用 key_type 的範例,請參閱 範例。

lower_bound

傳回迭代器,指向 map 中索引鍵值等於或大於指定索引鍵值的第一個元素。

iterator lower_bound(const Key& key);

const_iterator lower_bound(const Key& key) const;

參數

key
要與所搜尋之對應中元素的排序鍵比較的引數索引鍵值。

傳回值

iteratorconst_iterator ,定址物件是對應中索引鍵等於或大於引數索引鍵的專案位置,如果找不到索引鍵相符專案,則定址中最後 map 一個專案之後的位置。

如果將 的 lower_bound 傳回值指派給 const_iterator ,則無法修改 map 物件。 如果 的 lower_bound 傳回值指派給 iterator ,則可以修改 map 物件。

範例

// map_lower_bound.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;
   map <int, int> :: const_iterator m1_AcIter, m1_RcIter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );

   m1_RcIter = m1.lower_bound( 2 );
   cout << "The first element of map m1 with a key of 2 is: "
        << m1_RcIter -> second << "." << endl;

   // If no match is found for this key, end( ) is returned
   m1_RcIter = m1. lower_bound ( 4 );

   if ( m1_RcIter == m1.end( ) )
      cout << "The map m1 doesn't have an element "
           << "with a key of 4." << endl;
   else
      cout << "The element of map m1 with a key of 4 is: "
           << m1_RcIter -> second << "." << endl;

   // The element at a specific location in the map can be found
   // using a dereferenced iterator addressing the location
   m1_AcIter = m1.end( );
   m1_AcIter--;
   m1_RcIter = m1. lower_bound ( m1_AcIter -> first );
   cout << "The element of m1 with a key matching "
        << "that of the last element is: "
        << m1_RcIter -> second << "." << endl;
}
The first element of map m1 with a key of 2 is: 20.
The map m1 doesn't have an element with a key of 4.
The element of m1 with a key matching that of the last element is: 30.

map

建構一個空的 map,或是某個其他 map 之全部或部分複本的 map。

map();

explicit map(
    const Traits& Comp);

map(
    const Traits& Comp,
    const Allocator& Al);

map(
    const map& Right);

map(
    map&& Right);

map(
    initializer_list<value_type> IList);

map(
    initializer_list<value_type> IList,
    const Traits& Comp);

map(
    initializer_list<value_type> IList,
    const Traits& Comp,
    const Allocator& Allocator);

template <class InputIterator>
map(
    InputIterator First,
    InputIterator Last);

template <class InputIterator>
map(
    InputIterator First,
    InputIterator Last,
    const Traits& Comp);

template <class InputIterator>
map(
    InputIterator First,
    InputIterator Last,
    const Traits& Comp,
    const Allocator& Al);

參數

Al
要用於此 map 物件的儲存體配置器類別,預設為 Allocator

Comp
類型為 const Traits 並用來排序 map 中元素的比較函式,預設為 hash_compare

Right
要從中複製所建構之集合的對應。

First
要複製的元素範圍中第一個元素的位置。

Last
超出要複製之元素範圍的第一個元素的位置。

IList
要從中複製元素的 initializer_list。

備註

所有建構函式都會儲存一種配置器物件類型,可管理對應記憶體儲存體,稍後可呼叫 get_allocator 傳回 。 在類別宣告以及用來取代替代配置器的前置處理巨集中,經常會省略 allocator 參數。

所有建構函式都會將其 map 初始化。

所有建構函式都會儲存類型為 Traits 的函式物件,用來建立對應索引鍵之間的順序,稍後可藉由呼叫 key_comp 傳回。

前三個建構函式會指定空的初始對應,第二個建構函式會指定要用於建立元素順序的比較函式類型 Comp ,以及第三個明確指定要使用的配置器類型 ( Al ) 。 關鍵字 explicit 會隱藏某些類型的自動類型轉換。

第四個建構函式會指定 map Right 的複本。

第五個建構函式會藉由移動 Right 來指定 map 的複本。

第 6、7 和第 8 個建構函式會使用 initializer_list 從中複製成員的 。

接下來的三個建構函式會複製 map 的範圍 [First, Last),其中會以越來越明確的方式指定類別 Traits 的比較函式及配置器的類型。

範例

// map_map.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main()
{
    using namespace std;
    typedef pair <int, int> Int_Pair;
    map <int, int>::iterator m1_Iter, m3_Iter, m4_Iter, m5_Iter, m6_Iter, m7_Iter;
    map <int, int, less<int> >::iterator m2_Iter;

    // Create an empty map m0 of key type integer
    map <int, int> m0;

    // Create an empty map m1 with the key comparison
    // function of less than, then insert 4 elements
    map <int, int, less<int> > m1;
    m1.insert(Int_Pair(1, 10));
    m1.insert(Int_Pair(2, 20));
    m1.insert(Int_Pair(3, 30));
    m1.insert(Int_Pair(4, 40));

    // Create an empty map m2 with the key comparison
    // function of greater than, then insert 2 elements
    map <int, int, less<int> > m2;
    m2.insert(Int_Pair(1, 10));
    m2.insert(Int_Pair(2, 20));

    // Create a map m3 with the
    // allocator of map m1
    map <int, int>::allocator_type m1_Alloc;
    m1_Alloc = m1.get_allocator();
    map <int, int> m3(less<int>(), m1_Alloc);
    m3.insert(Int_Pair(3, 30));

    // Create a copy, map m4, of map m1
    map <int, int> m4(m1);

    // Create a map m5 by copying the range m1[ first,  last)
    map <int, int>::const_iterator m1_bcIter, m1_ecIter;
    m1_bcIter = m1.begin();
    m1_ecIter = m1.begin();
    m1_ecIter++;
    m1_ecIter++;
    map <int, int> m5(m1_bcIter, m1_ecIter);

    // Create a map m6 by copying the range m4[ first,  last)
    // and with the allocator of map m2
    map <int, int>::allocator_type m2_Alloc;
    m2_Alloc = m2.get_allocator();
    map <int, int> m6(m4.begin(), ++m4.begin(), less<int>(), m2_Alloc);

    cout << "m1 =";
    for (auto i : m1)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    cout << "m2 =";
    for(auto i : m2)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    cout << "m3 =";
    for (auto i : m3)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    cout << "m4 =";
    for (auto i : m4)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    cout << "m5 =";
    for (auto i : m5)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    cout << "m6 =";
    for (auto i : m6)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    // Create a map m7 by moving m5
    cout << "m7 =";
    map<int, int> m7(move(m5));
    for (auto i : m7)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    // Create a map m8 by copying in an initializer_list
    map<int, int> m8{ { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } } };
    cout << "m8: = ";
    for (auto i : m8)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    // Create a map m9 with an initializer_list and a comparator
    map<int, int> m9({ { 5, 5 }, { 6, 6 }, { 7, 7 }, { 8, 8 } }, less<int>());
    cout << "m9: = ";
    for (auto i : m9)
        cout << i.first << " " << i.second << ", ";
    cout << endl;

    // Create a map m10 with an initializer_list, a comparator, and an allocator
    map<int, int> m10({ { 9, 9 }, { 10, 10 }, { 11, 11 }, { 12, 12 } }, less<int>(), m9.get_allocator());
    cout << "m10: = ";
    for (auto i : m10)
        cout << i.first << " " << i.second << ", ";
    cout << endl;
}

mapped_type

一種類型,代表儲存在 map 中的資料。

typedef Type mapped_type;

備註

此類型 mapped_type 與類別的 Type 範本參數同義。

如需 的詳細資訊 Type ,請參閱 map 類別 主題。

範例

value_type如需如何宣告和使用 mapped_type 的範例,請參閱 範例。

max_size

傳回對應的最大長度。

size_type max_size() const;

傳回值

map 的最大可能長度。

範例

// map_max_size.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;
   map <int, int> :: size_type i;

   i = m1.max_size( );
   cout << "The maximum possible length "
        << "of the map is " << i << "."
        << endl << "(Magnitude is machine specific.)";
}

operator[]

將具有特定索引鍵值的項目插入對應中。

Type& operator[](const Key& key);

Type& operator[](Key&& key);

參數

key
要插入之專案的索引鍵值。

傳回值

所插入項目之資料值的參考。

備註

如果找不到引數索引鍵值,則會與資料類型的預設值一起插入。

operator[] 可用來將元素插入到對應 m 中,方法是使用 m[key] = DataValue;,其中 DataValue 是索引鍵值為 key 之元素的 mapped_type 值。

當使用 operator[] 插入項目時,傳回的參考不會指出插入是變更預先存在的項目,還是建立新的項目。 成員函式 findinsert 可用來判斷具有指定索引鍵的專案是否已經在插入之前存在。

範例

// map_op_insert.cpp
// compile with: /EHsc
#include <map>
#include <iostream>
#include <string>

int main( )
{
   using namespace std;
   typedef pair <const int, int> cInt2Int;
   map <int, int> m1;
   map <int, int> :: iterator pIter;

   // Insert a data value of 10 with a key of 1
   // into a map using the operator[] member function
   m1[ 1 ] = 10;

   // Compare other ways to insert objects into a map
   m1.insert ( map <int, int> :: value_type ( 2, 20 ) );
   m1.insert ( cInt2Int ( 3, 30 ) );

   cout  << "The keys of the mapped elements are:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> first;
   cout << "." << endl;

   cout  << "The values of the mapped elements are:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> second;
   cout << "." << endl;

   // If the key already exists, operator[]
   // changes the value of the datum in the element
   m1[ 2 ] = 40;

   // operator[] will also insert the value of the data
   // type's default constructor if the value is unspecified
   m1[5];

   cout  << "The keys of the mapped elements are now:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> first;
   cout << "." << endl;

   cout  << "The values of the mapped elements are now:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> second;
   cout << "." << endl;

// insert by moving key
    map<string, int> c2;
    string str("abc");
    cout << "c2[move(str)] == " << c2[move(str)] << endl;
    cout << "c2["abc"] == " << c2["abc"] << endl;

    return (0);
}
The keys of the mapped elements are: 1 2 3.
The values of the mapped elements are: 10 20 30.
The keys of the mapped elements are now: 1 2 3 5.
The values of the mapped elements are now: 10 40 30 0.
c2[move(str)] == 0
c2["abc"] == 1

operator=

用另一個對應複本取代對應的項目。

map& operator=(const map& right);
map& operator=(map&& right);

參數

right
map要複製到 的 map

備註

清除 map 中任何現有的元素之後,operator= 會將 right 的內容複製或移到 map 中。

範例

// map_operator_as.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
   {
   using namespace std;
   map<int, int> v1, v2, v3;
   map<int, int>::iterator iter;

   v1.insert(pair<int, int>(1, 10));

   cout << "v1 = " ;
   for (iter = v1.begin(); iter != v1.end(); iter++)
      cout << iter->second << " ";
   cout << endl;

   v2 = v1;
   cout << "v2 = ";
   for (iter = v2.begin(); iter != v2.end(); iter++)
      cout << iter->second << " ";
   cout << endl;

// move v1 into v2
   v2.clear();
   v2 = move(v1);
   cout << "v2 = ";
   for (iter = v2.begin(); iter != v2.end(); iter++)
      cout << iter->second << " ";
   cout << endl;
   }

pointer

一種類型,提供 map 中元素的指標。

typedef typename allocator_type::pointer pointer;

備註

pointer 別可用來修改專案的值。

在大部分情況下, iterator 應該使用 來存取對應物件中的專案。

rbegin

傳回迭代器,定址對象是反轉 map 中的第一個元素。

const_reverse_iterator rbegin() const;

reverse_iterator rbegin();

傳回值

反轉雙向迭代器,定址對象是反轉 map 中的第一個元素,或未反轉 map 中的最後一個元素。

備註

rbegin 與反轉對應搭配使用,就像與地圖搭配使用一樣 begin

如果 的 rbegin 傳回值指派給 const_reverse_iterator ,則無法修改 map 物件。 如果將 rbegin 的傳回值指派給 reverse_iterator,則可以修改 map 物件。

rbegin 可用來向後逐一查看 map。

範例

// map_rbegin.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;

   map <int, int> :: iterator m1_Iter;
   map <int, int> :: reverse_iterator m1_rIter;
   map <int, int> :: const_reverse_iterator m1_crIter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );

   m1_rIter = m1.rbegin( );
   cout << "The first element of the reversed map m1 is "
        << m1_rIter -> first << "." << endl;

   // begin can be used to start an iteration
   // through a map in a forward order
   cout << "The map is: ";
   for ( m1_Iter = m1.begin( ) ; m1_Iter != m1.end( ); m1_Iter++)
      cout << m1_Iter -> first << " ";
      cout << "." << endl;

   // rbegin can be used to start an iteration
   // through a map in a reverse order
   cout << "The reversed map is: ";
   for ( m1_rIter = m1.rbegin( ) ; m1_rIter != m1.rend( ); m1_rIter++)
      cout << m1_rIter -> first << " ";
      cout << "." << endl;

   // A map element can be erased by dereferencing to its key
   m1_rIter = m1.rbegin( );
   m1.erase ( m1_rIter -> first );

   m1_rIter = m1.rbegin( );
   cout << "After the erasure, the first element "
        << "in the reversed map is "
        << m1_rIter -> first << "." << endl;
}
The first element of the reversed map m1 is 3.
The map is: 1 2 3 .
The reversed map is: 3 2 1 .
After the erasure, the first element in the reversed map is 2.

reference

一種類型,提供對儲存在 map 中元素的參考。

typedef typename allocator_type::reference reference;

範例

// map_reference.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );

   // Declare and initialize a const_reference &Ref1
   // to the key of the first element
   const int &Ref1 = ( m1.begin( ) -> first );

   // The following line would cause an error because the
   // non-const_reference can't be used to access the key
   // int &Ref1 = ( m1.begin( ) -> first );

   cout << "The key of first element in the map is "
        << Ref1 << "." << endl;

   // Declare and initialize a reference &Ref2
   // to the data value of the first element
   int &Ref2 = ( m1.begin( ) -> second );

   cout << "The data value of first element in the map is "
        << Ref2 << "." << endl;

   //The non-const_reference can be used to modify the
   //data value of the first element
   Ref2 = Ref2 + 5;
   cout << "The modified data value of first element is "
        << Ref2 << "." << endl;
}
The key of first element in the map is 1.
The data value of first element in the map is 10.
The modified data value of first element is 15.

rend

傳回迭代器,定址對象是反轉 map 中最後一個元素後面的位置。

const_reverse_iterator rend() const;

reverse_iterator rend();

傳回值

反轉雙向迭代器,定址對象是反轉 map 中最後一個元素後面的位置 (未反轉 map 中第一個元素前面的位置)。

備註

rend 與反轉對應搭配使用,就像與地圖搭配使用一樣 end

如果 的 rend 傳回值指派給 const_reverse_iterator ,則無法修改 map 物件。 如果將 rend 的傳回值指派給 reverse_iterator,則可以修改 map 物件。

rend 可以用來測試反轉迭代器是否已到達其 map 的結尾。

rend 所傳回的值不應該取值。

範例

// map_rend.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;

   map <int, int> :: iterator m1_Iter;
   map <int, int> :: reverse_iterator m1_rIter;
   map <int, int> :: const_reverse_iterator m1_crIter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );

   m1_rIter = m1.rend( );
   m1_rIter--;
   cout << "The last element of the reversed map m1 is "
        << m1_rIter -> first << "." << endl;

   // begin can be used to start an iteration
   // through a map in a forward order
   cout << "The map is: ";
   for ( m1_Iter = m1.begin( ) ; m1_Iter != m1.end( ); m1_Iter++)
      cout << m1_Iter -> first << " ";
      cout << "." << endl;

   // rbegin can be used to start an iteration
   // through a map in a reverse order
   cout << "The reversed map is: ";
   for ( m1_rIter = m1.rbegin( ) ; m1_rIter != m1.rend( ); m1_rIter++)
      cout << m1_rIter -> first << " ";
      cout << "." << endl;

   // A map element can be erased by dereferencing to its key
   m1_rIter = --m1.rend( );
   m1.erase ( m1_rIter -> first );

   m1_rIter = m1.rend( );
   m1_rIter--;
   cout << "After the erasure, the last element "
        << "in the reversed map is "
        << m1_rIter -> first << "." << endl;
}
The last element of the reversed map m1 is 1.
The map is: 1 2 3 .
The reversed map is: 3 2 1 .
After the erasure, the last element in the reversed map is 2.

reverse_iterator

一種類型,提供可讀取或修改反轉 map 中元素的雙向迭代器。

typedef std::reverse_iterator<iterator> reverse_iterator;

備註

類型 reverse_iterator 無法修改專案的值,並且用來反向逐一查看對應。

reverse_iterator由 map 所定義的 指向 屬於 的物件 value_type ,其 pair<const Key, Type> 第一個成員是 元素的索引鍵,而第二個成員是 元素所持有的對應日期。

若要取值 reverse_iterator 指向對應中元素的 rIter ,請使用 -> 運算子。

若要存取元素的索引鍵值,請使用 rIter - > first ,這相當於 (* rIter )。 first。 若要存取專案的對應日期值,請使用 rIter - > second ,這相當於 (* rIter )。 first

範例

rbegin如需如何宣告和使用 reverse_iterator 的範例,請參閱 範例。

size

傳回 map 中項目的數目。

size_type size() const;

傳回值

地圖目前的長度。

範例

下列範例示範如何使用 map::size 成員函式。

// map_size.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main()
{
    using namespace std;
    map<int, int> m1, m2;
    map<int, int>::size_type i;
    typedef pair<int, int> Int_Pair;

    m1.insert(Int_Pair(1, 1));
    i = m1.size();
    cout << "The map length is " << i << "." << endl;

    m1.insert(Int_Pair(2, 4));
    i = m1.size();
    cout << "The map length is now " << i << "." << endl;
}
The map length is 1.
The map length is now 2.

size_type

一種不帶正負號的整數類型,可代表 map 中的元素數目。

typedef typename allocator_type::size_type size_type;

範例

如需如何宣告和使用 size_type 的範例 size ,請參閱範例。

swap

交換兩個對應的項目。

void swap(
    map<Key, Type, Traits, Allocator>& right);

參數

right
提供要與目標 map 交換之元素的引數 map。

備註

任何參考、指標或迭代器只要指定的元素是在交換元素的兩個 map 中,成員函式就不會使其失效。

範例

// map_swap.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1, m2, m3;
   map <int, int>::iterator m1_Iter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );
   m2.insert ( Int_Pair ( 10, 100 ) );
   m2.insert ( Int_Pair ( 20, 200 ) );
   m3.insert ( Int_Pair ( 30, 300 ) );

   cout << "The original map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
   cout   << "." << endl;

   // This is the member function version of swap
   //m2 is said to be the argument map; m1 the target map
   m1.swap( m2 );

   cout << "After swapping with m2, map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
   cout  << "." << endl;

   // This is the specialized template version of swap
   swap( m1, m3 );

   cout << "After swapping with m3, map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
   cout   << "." << endl;
}
The original map m1 is: 10 20 30.
After swapping with m2, map m1 is: 100 200.
After swapping with m3, map m1 is: 300.

upper_bound

傳回迭代器,指向 map 中索引鍵值大於指定索引鍵值的第一個元素。

iterator upper_bound(const Key& key);

const_iterator upper_bound(const Key& key) const;

參數

key
要與所搜尋之對應中元素的排序鍵值比較的引數索引鍵值。

傳回值

iteratorconst_iterator ,定址物件是對應中索引鍵大於引數索引鍵的專案位置,如果找不到索引鍵相符專案,則定址中最後一 map 個專案之後的位置。

如果傳回值指派給 const_iterator ,則無法修改 map 物件。 如果傳回值指派給 iterator ,則可以修改 map 物件。

範例

// map_upper_bound.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   map <int, int> m1;
   map <int, int> :: const_iterator m1_AcIter, m1_RcIter;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );

   m1_RcIter = m1.upper_bound( 2 );
   cout << "The first element of map m1 with a key "
        << "greater than 2 is: "
        << m1_RcIter -> second << "." << endl;

   // If no match is found for the key, end is returned
   m1_RcIter = m1. upper_bound ( 4 );

   if ( m1_RcIter == m1.end( ) )
      cout << "The map m1 doesn't have an element "
           << "with a key greater than 4." << endl;
   else
      cout << "The element of map m1 with a key > 4 is: "
           << m1_RcIter -> second << "." << endl;

   // The element at a specific location in the map can be found
   // using a dereferenced iterator addressing the location
   m1_AcIter = m1.begin( );
   m1_RcIter = m1. upper_bound ( m1_AcIter -> first );
   cout << "The 1st element of m1 with a key greater than\n"
        << "that of the initial element of m1 is: "
        << m1_RcIter -> second << "." << endl;
}
The first element of map m1 with a key greater than 2 is: 30.
The map m1 doesn't have an element with a key greater than 4.
The 1st element of m1 with a key greater than
that of the initial element of m1 is: 20.

value_comp

成員函式會傳回函式物件,此物件可藉由比較 map 中元素的索引鍵值來判斷這些元素的順序。

value_compare value_comp() const;

傳回值

傳回 map 用來排序其元素的比較函式物件。

備註

對於 map m,如果兩個元素 e1( k1 d1 ) 和 e2( k2 d2 ) 是 類型的 value_type 物件,其中 k1 和 k1 是類型的索引鍵 key_type ,而 d1 d2 是其類型的 mapped_type 資料類型,則 m.value_comp(e1, e2) 相當於 。 m.key_comp(k1, k2) 預存物件會定義成員函式

bool operator( value_type& left, value_type& right);

如果 的索引鍵值 left 在 之前,且 不等於排序次序中的 索引鍵值 right ,則會傳回 true

範例

// map_value_comp.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;

   map <int, int, less<int> > m1;
   map <int, int, less<int> >::value_compare vc1 = m1.value_comp( );
   pair< map<int,int>::iterator, bool > pr1, pr2;

   pr1= m1.insert ( map <int, int> :: value_type ( 1, 10 ) );
   pr2= m1.insert ( map <int, int> :: value_type ( 2, 5 ) );

   if( vc1( *pr1.first, *pr2.first ) == true )
   {
      cout << "The element ( 1,10 ) precedes the element ( 2,5 )."
           << endl;
   }
   else
   {
      cout << "The element ( 1,10 ) does not precede the element ( 2,5 )."
           << endl;
   }

   if(vc1( *pr2.first, *pr1.first ) == true )
   {
      cout << "The element ( 2,5 ) precedes the element ( 1,10 )."
           << endl;
   }
   else
   {
      cout << "The element ( 2,5 ) does not precede the element ( 1,10 )."
           << endl;
   }
}
The element ( 1,10 ) precedes the element ( 2,5 ).
The element ( 2,5 ) does not precede the element ( 1,10 ).

value_type

以元素形式儲存在 map 中的物件類型。

typedef pair<const Key, Type> value_type;

範例

// map_value_type.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   typedef pair <const int, int> cInt2Int;
   map <int, int> m1;
   map <int, int> :: key_type key1;
   map <int, int> :: mapped_type mapped1;
   map <int, int> :: value_type value1;
   map <int, int> :: iterator pIter;

   // value_type can be used to pass the correct type
   // explicitly to avoid implicit type conversion
   m1.insert ( map <int, int> :: value_type ( 1, 10 ) );

   // Compare other ways to insert objects into a map
   m1.insert ( cInt2Int ( 2, 20 ) );
   m1[ 3 ] = 30;

   // Initializing key1 and mapped1
   key1 = ( m1.begin( ) -> first );
   mapped1 = ( m1.begin( ) -> second );

   cout << "The key of first element in the map is "
        << key1 << "." << endl;

   cout << "The data value of first element in the map is "
        << mapped1 << "." << endl;

   // The following line would cause an error because
   // the value_type isn't assignable
   // value1 = cInt2Int ( 4, 40 );

   cout  << "The keys of the mapped elements are:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> first;
   cout << "." << endl;

   cout  << "The values of the mapped elements are:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> second;
   cout << "." << endl;
}

另請參閱

容器
C++ 標準程式庫中的執行緒安全
C++ 標準程式庫參考