set构造函数有以下五种用途:
默认构造函数:用于构造具有零个元素的空set容器。
范围构造函数:用于构造内容范围为[first,last)的容器。
复制构造函数:用于构造带有现有容器元素副本的集合。
move构造函数:用于使用move语义与其他元素一起构造容器。
初始化程序列表构造函数:用于构造带有初始化程序列表内容的集合。
explicit set (const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); //到 C++ 11 explicit set (const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); explicit set (const allocator_type& alloc); //从C ++ 11开始
template <class InputIterator> set (InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); //到 C++ 11 template <class InputIterator> set (InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const allocator_type& = allocator_type()); //从C ++ 11开始
set (const set& x); //到 C++ 11 set (const set& x); set (const set& x, const allocator_type& alloc); //从C ++ 11开始
set (set&& x); set (set&& x, const allocator_type& alloc); //从C ++ 11开始
set (initializer_list<value_type> il, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); //从C ++ 11开始
comp:比较函数对象,它接受两个关键参数,如果第一个参数在第二个参数之前,则返回true,否则返回false。默认情况下,它使用less <key_type>谓词。
alloc:一个分配器对象,用于此容器的所有内存分配。
first:将迭代器输入范围内的第一个位置。
last:将迭代器输入到范围中的最后一个位置。
x:另一个相同类型的set对象。
il:一个初始化器列表对象,将从中复制元素。
构造函数从不返回任何值。
对于空的构造函数和移动的构造函数,复杂性将是恒定的。
对于所有其他情况,如果元素已经排序,则迭代器之间的距离的复杂度将是线性的。
如果set容器的元素在move构造函数中移动,则使与x相关的所有指针,迭代器和引用无效。
访问所有复制的元素。
万一引发异常,则没有任何效果。
让我们看一下默认构造函数的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
// 默认构造函数
set<char> s;
int size = s.size();
cout << "集合s的大小 = " << size;
return 0;
}输出:
集合s的大小 = 0
在上面的示例中,s是一个空集,因此size为0。
让我们来看一个范围构造函数的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
int evens[] = {2,4,6,8,10};
// 范围构造函数
set<int> myset (evens, evens+5);
cout << "集合容器myset的大小为 : " << myset.size();
return 0;
}输出:
集合容器myset的大小为: 5
在上面的示例中,set myset由evens元素构成。
让我们来看一个简单的复制构造函数示例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
//默认构造函数
std::set<int> s1;
s1.insert(5);
s1.insert(10);
cout << "集合容器s1的大小为 : " << s1.size();
// 复制构造函数
set<int> s2(s1);
cout << "\n新集合容器s2的大小为 : " << s2.size();
return 0;
}输出:
集合容器s1的大小为 : 2 新集合容器s2的大小为 : 2
在上面的示例中,s2是s1集合的拷贝副本。
我们来看一个简单的移动构造函数示例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
// 默认构造函数
set<char> s1;
s1.insert('x');
s1.insert('y');
cout << "集合容器s1的大小为 : " << s1.size();
// Move 构造函数
set<char> s2(move(s1));
cout << "\n新集合容器s2的大小为 : " << s2.size();
return 0;
}输出:
集合容器s1的大小为 : 2 新集合容器s2的大小为 : 2
在上面的示例中,s1的内容被移至s2 set。
让我们看一个简单的初始化列表构造函数示例:
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
// 初始化列表构造函数
set<string> fruit {
"orange", "apple", "mango", "peach", "grape"
};
cout << "容器内fruit的大小为 : " << fruit.size();
return 0;
}输出:
容器内fruit的大小为 : 5
上面的示例创建一个以字符串为键的set水果,并使用initializer_list对其进行初始化。