如何在C ++ STL中插入一系列元素
C ++中的Set是一种关联容器类型,其中每个元素都必须是唯一的,因为元素的值标识它。值以特定的排序顺序存储,即升序或降序。
语法 :
set<datatype> set_name;
与Set相关的一些基本函数:
- begin():返回指向集合中第一个元素的迭代器。
- end():返回指向集合中最后一个元素之后的理论元素的迭代器。
- size():返回集合中元素的数量。
- max_size():返回集合可容纳的最大元素数。
- empty():返回集合是否为空。
将迭代器范围插入Set
它需要范围并在O(N log(N))时间内逐个将元素插入BST中,如果它尚未存在于其中。
语法 :
set_name.insert(iterator Starting_position, iterator Ending_position);
注意 :它插入Starting_position,Ending_position)的元素,这意味着不包括Ending_position元素。
示例:
// C ++程序插入
//从数组中插入元素
//在set中使用
// Iterator Range
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
set<int> s;
int arr[] = { 1, 2, 4, 3, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
s.clear();
// 将数组的元素插入set中
s.insert(arr, arr + N);
cout << "插入大小为:" << N << endl;
cout << "set大小:" << s.size() << endl;
//输出set中的元素
对于(auto& i:s) {
cout << i << "";
}
return 0;
}
输出
插入大小为:5
set大小:5
1 2 3 4 5
示例2:
// C ++程序插入
//从向量中插入元素
//在set中使用
// Iterator Range
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
vector <int> v = {1, 2, 4, 3, 5 };
set <int> s;
//将向量的元素插入set中
s.insert(v.begin(), v.end());
cout << "插入大小为:" << v.size()
<< endl;
cout << "set大小:" << s.size() << endl;
//输出set中的元素
对于(auto& i:s) {
cout << i << "";
}
cout << endl;
return 0;
}
输出
插入大小为:5
set大小:5
1 2 3 4 5