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
下面是 set 和 list 之间的表格差异:
从上面的代码可以看出,在集合中插入值 {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. |