📜  C ++ STL中std :: set与std :: vector之间的区别

📅  最后修改于: 2021-06-01 01:18:56             🧑  作者: Mango

向量:向量是类似于动态数组的容器,能够在插入或删除新元素时调整大小。它是标准模板库或STL的模板,可为程序提供更大的灵活性。向量的元素放置在连续的存储中,并使用迭代器遍历。

例子:

vector  v;
v.push_back(1);
v.push_back(2);
v.clear();

下面是C++中向量的实现:

C++
// C++ program to demonstrate the
// working of vector in cpp
#include 
using namespace std;
  
// Driver Code
int main()
{
    vector v;
  
    // Inserting elements in vector
    v.push_back(11);
    v.push_back(6);
    v.push_back(12);
    v.push_back(0);
    v.push_back(0);
  
    // Elements are stored in the
    // order of insertion with the
    // duplicate element
    cout << "Elements in vector are:\n";
    for (auto it : v) {
        cout << it << " ";
    }
  
    return 0;
}


C++
// C++ program to demonstrate the
// working of set in c++
#include 
using namespace std;
  
// Driver Code
int main()
{
    set s;
  
    // Insert elements into the set
    s.insert(11);
    s.insert(6);
    s.insert(12);
    s.insert(0);
  
    // Duplicate elements
    s.insert(0);
  
    cout << "Elements in set:\n";
  
    // The inserted elements get sorted
  
    // Print the elements of the set
    for (auto it : s) {
        cout << it << " ";
    }
  
    return 0;
}


输出:
Elements in vector are:
11 6 12 0 0

Set Set也是标准模板库或STL的模板之一。它是包含唯一元素的容器,其值一旦添加到集合中就无法修改,但可以删除或插入。集合中的元素始终以排序形式存储。

例子:

set  s;
s.insert(1);
s.insert(12);
int key = 1;
s.erase(key);

下面是C++中集合的实现:

C++

// C++ program to demonstrate the
// working of set in c++
#include 
using namespace std;
  
// Driver Code
int main()
{
    set s;
  
    // Insert elements into the set
    s.insert(11);
    s.insert(6);
    s.insert(12);
    s.insert(0);
  
    // Duplicate elements
    s.insert(0);
  
    cout << "Elements in set:\n";
  
    // The inserted elements get sorted
  
    // Print the elements of the set
    for (auto it : s) {
        cout << it << " ";
    }
  
    return 0;
}
输出:
Elements in set:
0 6 11 12

向量和集合之间的表格差异

Vector

Set

Elements of the vector are unsorted. Elements of sets are always sorted.
It can contain duplicate elements. It contains only unique elements.
The vector is unordered. Set is ordered.
The time complexity for insertion of a new element is O(1). The time complexity for the insertion of a new element is O(log N).
Vector is faster for insertion and deletion of elements at the end of the container. Set is faster for insertion and deletion of elements at the middle of the container.

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”