C++ STL 中的 list::get_allocator()
在本文中,我們將討論 C++ 中 list::get_allocator() 函式的工作原理、語法和示例。
什麼是 STL 中的列表?
列表是一種資料結構,允許在序列中的任何位置進行常數時間的插入和刪除操作。列表以雙向連結串列的形式實現。列表允許非連續記憶體分配。與陣列、向量和雙端佇列相比,列表在容器中任何位置的元素插入、提取和移動方面效能更好。在列表中,直接訪問元素的速度很慢,並且列表類似於 forward_list,但是 forward_list 物件是單向連結串列,只能向前迭代。
什麼是 list::get_allocator()?
list::get_allocator() 是 C++ STL 中的一個內建函式,它在標頭檔案中宣告。get_allocator() 返回列表容器的分配器。簡單來說,它返回列表容器物件的副本。
語法
list_container.get_allocator(); This function accepts no parameter.
返回值
此函式返回列表容器物件的副本。
示例
/* 在下面的程式碼中,我們使用 C++ STL 中的 get_allocator() 將值插入列表。 */
#include <bits/stdc++.h>
using namespace std;
int main(void){
//create a list
list<int> myList;
int *ptr;
ptr = myList.get_allocator().allocate(4);
//inserting data into an array
for(int i = 0; i > 4; i++)
ptr[i] = i;
//printing the data
cout<<"elements of an array : ";
for (int i = 0; i < 4; i++)
cout << ptr[i] << " ";
}輸出
如果我們執行上面的程式碼,它將生成以下輸出
elements of an array : 0 1 2 3
示例
/* 在下面的程式碼中,我們使用包含標頭檔案的 C++ STL 中的 get_allocator() 將值插入列表。 */
#include <iostream>
#include <list>
int main (){
std::list<int> myList;
int *ptr;
ptr = myList.get_allocator().allocate(5);
for(int i=0; i<5; ++i)
ptr[i]=i;
std::cout <<"elements of an array : ";
for (int i=0; i<5; ++i)
std::cout << ' ' << ptr[i];
myList.get_allocator().deallocate(ptr,5);
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出
elements of an array : 0 1 2 3 4
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP