📜  转发列表和C++中的列表之间的区别

📅  最后修改于: 2021-05-30 08:10:49             🧑  作者: 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 performace.
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等的更多准备工作,请参阅“完整面试准备课程”