C++ Deque::get_allocator() 函式



C++ 的std::deque::get_allocator()函式用於返回與deque關聯的分配器物件的副本。此分配器物件負責管理deque中元素的記憶體分配和釋放。透過訪問分配器,我們可以控制或自定義記憶體管理。

語法

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

allocator_type get_allocator() const noexcept;

引數

它不接受任何引數。

返回值

它返回與deque關聯的分配器。

異常

此函式從不丟擲異常。

時間複雜度

此函式的時間複雜度為常數,即O(1)

示例

在下面的示例中,我們將考慮get_allocator()函式的基本用法。

#include <iostream>
#include <deque>
#include <memory>
int main()
{
    std::deque<char> a;
    std::allocator<char> x = a.get_allocator();
    char* y = x.allocate(1);
    x.construct(y, 'A');
    std::cout << "Value constructed in allocated memory: " << *y << std::endl;
    x.destroy(y);
    x.deallocate(y, 1);
    return 0;
}

輸出

以上程式碼的輸出如下:

Value constructed in allocated memory: A

示例

考慮以下示例,我們將使用與第一個deque相同的分配器來建立另一個deque。

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a = {1, 22,333,4444};
    std::deque<int> b(a.get_allocator());
    b.push_back(123);
    b.push_back(345);
    for (int val : b) {
        std::cout << val << " ";
    }
    std::cout << std::endl;
    return 0;
}

輸出

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

123 345 
deque.htm
廣告