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