向量:向量是类似于动态数组的容器,能够在插入或删除新元素时调整大小。它是标准模板库或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 也是 Standard Template Library 或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++ 和C++ STL 课程,了解语言和 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。