📜  std :: set和std :: list之间的区别

📅  最后修改于: 2021-05-20 05:57:11             🧑  作者: Mango

Set Set是一种关联容器,以排序的方式存储元素。集合中的所有元素都是唯一的,不能修改,但是可以删除或插入。它是C++中的标准模板库或STL的模板。

句法:

set  s

下面是说明相同内容的程序:

C++
// C++ program to demonstrate the
// working of set in c++
#include 
using namespace std;
  
// Driver code
int main()
{
    // Declaring a set
    set s;
  
    // Inserting elements
    // into the set
    s.insert(10);
    s.insert(5);
    s.insert(15);
    s.insert(1);
  
    // Insert the duplicate elements
    s.insert(1);
  
    cout << "Elements in set:\n";
  
    // Print the element stored in set
    for (auto it : s)
        cout << it << " ";
  
    return 0;
}


C++
// C++ program to demonstrate the
// working of list in cpp
#include 
using namespace std;
  
// Driver code
int main()
{
    // Declaring a list
    list l;
  
    // Inserting elements
    // in the list
    l.push_back(10);
    l.push_back(15);
    l.push_back(5);
    l.push_back(1);
    l.push_back(1);
    l.push_back(10);
  
    cout << "Elements in list:\n";
  
    // Print the elements of list
    for (auto it : l)
        cout << it << " ";
  
    return 0;
}


输出:
Elements in set:
1 5 10 15

列表列表是一种序列容器,其中元素存储在非连续的内存分配中。它被实现为一个双向链接列表,因此它可以双向提供迭代。

句法:

list  l;

下面是说明相同内容的程序:

C++

// C++ program to demonstrate the
// working of list in cpp
#include 
using namespace std;
  
// Driver code
int main()
{
    // Declaring a list
    list l;
  
    // Inserting elements
    // in the list
    l.push_back(10);
    l.push_back(15);
    l.push_back(5);
    l.push_back(1);
    l.push_back(1);
    l.push_back(10);
  
    cout << "Elements in list:\n";
  
    // Print the elements of list
    for (auto it : l)
        cout << it << " ";
  
    return 0;
}
输出:
Elements in list:
10 15 5 1 1 10

以下是集合和列表之间的表格差异

从上面的代码中可以看出,在集合中插入值{10、5、15、1、1}之后,元素将被排序,并且重复项不会存储在集合中。因此,它是无序的。但是在列表的情况下,元素按插入顺序精确存储,并且重复项也存储。因此,它是有序的。

S.No.

Set

List

1 Set is sorted and unordered The list is unsorted and ordered
2 Insertion cannot be done at the desired position Insertion can be done at any position using the insert() function
3 Takes logarithmic time for searching an element. Takes linear time for searching for an element.
4 Elements are unique. May contain duplicate elements.
5 Can contain only one null value. Can contain more than one null value.
6 Insertion and deletion take logarithmic time. Insertion and deletion take constant time.
7 Implemented in HashSet, LinkedHashSet, and TreeSet. Implemented in ArrayList and LinkedList.