📜  C++中前向列表和列表的区别

📅  最后修改于: 2021-09-15 01:46:09             🧑  作者: Mango

转发列表
前向列表是一个序列容器,允许对其数据进行单向顺序访问。它包含相同类型的数据。在 STL 中,它已经使用单向链表实现,插入和删除需要恒定的时间。前向列表的元素分散在内存中,通过链接将列表的每个元素与列表的下一个元素相关联来维护排序。因此,它可以有效地利用内存。它是从 C++11 版本开始引入的。
转发列表的实现:

C++
#include 
using namespace std;
int main()
{
    // Declaring forward list
    forward_list flist1;
 
    // Assigning values using assign()
    flist1.assign({ 10, 12, 13, 15 });
 
    // Displaying forward list
    cout << "The elements of forward list are : ";
    for (auto a : flist1)
        cout << a << " ";
    return 0;
}


C++
#include 
using namespace std;
int main()
{
    // Declaring a list
    list list1;
 
    // Assigning values using assign()
    list1.assign({ 1, 2, 10, 15 });
 
    // Displaying list
    cout << "The elements of list are : ";
    for (auto a : list1)
        cout << a << " ";
    return 0;
}


输出:
The elements of forward list are : 10 12 13 15

列表
List 也是一个序列容器,允许对其数据进行双向顺序访问。它包含相同类型的数据。在 STL 中,它是使用双向链表实现的,它需要恒定的插入和删除时间。它允许非连续的内存分配。列表中的每个元素都与指向它后面和前面的元素的链接相关联。由于其恒定的插入和删除时间和双向顺序访问,它被广泛用于排序算法。
清单的实施:

C++

#include 
using namespace std;
int main()
{
    // Declaring a list
    list list1;
 
    // Assigning values using assign()
    list1.assign({ 1, 2, 10, 15 });
 
    // Displaying list
    cout << "The elements of list are : ";
    for (auto a : list1)
        cout << a << " ";
    return 0;
}
输出:
The elements of list are : 1 2 10 15

前向列表和列表之间的表格区别:

Forward list List
Implemented using Singly Linked List Implemented using Doubly Linked List
Consumes relatively less memory Consumes relatively more memory
Less overhead in insertion and removal elements due to less pointer per node, thus it gives better performance. More overhead in insertion and removal elements due to more pointer per node, thus it gives poor performance.
Sequential access in forward direction Sequential access in both forward and reverse direction
Generally used when bidirectional sequential access is needed like for implementing chaining in hashing, adjacency list representation of graph, etc. Generally used when unidirectional sequential access is needed like for implementing binary tree, hash table, stack, etc.
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程