C++ multimap::get_allocator() 函式



C++ 的std::multimap::get_allocator()函式用於返回 multimap 用於管理記憶體的分配器物件。C++ 中的分配器定義了容器元素要使用的記憶體模型。此函式提供對分配器的訪問,從而可以執行自定義記憶體分配和釋放等操作。此函式的時間複雜度為常數,即 O(1)。

語法

以下是 std::multimap::get_allocator() 函式的語法。

allocator_type get_allocator() const noexcept;

引數

它不接受任何引數。

返回值

此函式返回與 multimap 關聯的分配器。

示例

讓我們來看下面的例子,我們將演示 get_allocator() 函式的使用。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, int> a;
    auto x = a.get_allocator();
    std::pair<const int, int>* y = x.allocate(3);
    std::cout << "Allocated Memory At: " << y << std::endl;
    x.deallocate(y, 3);
    return 0;
}

輸出

以上程式碼的輸出如下:

Allocated Memory At: 0x55e143b18eb0

示例

考慮以下示例,我們將分配元素陣列。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    auto x = a.get_allocator();
    auto y = x.allocate(3);
    for (int i = 0; i < 3; ++i) {
        x.construct(y + i, std::pair<const int, std::string>(i, "value" + std::to_string(i)));
    }
    for (int i = 0; i < 3; ++i) {
        std::cout << (y + i)->first << " : " << (y + i)->second << std::endl;
    }
    for (int i = 0; i < 3; ++i) {
        x.destroy(y + i);
    }
    x.deallocate(y, 3);
    return 0;
}

輸出

以下是以上程式碼的輸出:

0 : value0
1 : value1
2 : value2

示例

在下面的示例中,我們將分配和構造多個元素。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, int> a;
    auto x = a.get_allocator();
    std::pair<const int, int>* p = x.allocate(2);
    x.construct(&p[0], std::make_pair(1, 11));
    x.construct(&p[1], std::make_pair(2, 22));
    for (int i = 0; i < 2; ++i) {
        std::cout << "Element " << i << ": (" << p[i].first << ", " << p[i].second << ")" << std::endl;
    }
    for (int i = 0; i < 2; ++i) {
        x.destroy(&p[i]);
    }
    x.deallocate(p, 3);
    return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Element 0: (1, 11)
Element 1: (2, 22)
multimap.htm
廣告