set构造函数有以下五种用途:
explicit set (const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); //until C++ 11 explicit set (const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); explicit set (const allocator_type& alloc); //since C++ 11
template <class InputIterator> set (InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); //until C++ 11 template <class InputIterator> set (InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const allocator_type& = allocator_type()); //since C++ 11
set (const set& x); //until C++ 11 set (const set& x); set (const set& x, const allocator_type& alloc); //since C++ 11
set (set&& x); set (set&& x, const allocator_type& alloc); //since C++ 11
set (initializer_list<value_type> il, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); //since C++ 11
comp - 一个比较函数对象,它接受两个关键参数,如果第一个参数在第二个参数之前,则返回true,否则返回false。默认情况下,它使用less <key_type>谓词。
alloc - 分配器对象用于此集合的所有内存分配。
first - 将迭代器输入到参数中的第一位置。
last - 将迭代器输入到参数中的最后一个位置。
x - 另一个相同类型的集合对象。
il - 要从中复制元素的初始化列表对象。
构造函数从不返回任何值。
让我们看一下默认构造函数的简单示例:
#include <iostream> #include <set> using namespace std; int main(void) { //默认构造函数 set<char> s; int size = s.size(); cout << "Size of set s = " << size; return 0; }
输出:
Size of set = 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 << "Size of set container myset is : " << myset.size(); return 0; }
输出:
Size of set container myset is: 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 << "Size of set container s1 is : " << s1.size(); //复制构造函数 set<int> s2(s1); cout << "\nSize of new set container s2 is : " << s2.size(); return 0; }
输出:
Size of set container s1 is : 2 Size of new set container s2 is : 2
在上面的示例中,s2是s1集的副本。
让我们看一个简单的移动构造函数例子:
#include <iostream> #include <set> using namespace std; int main(void) { //默认构造函数 set<char> s1; s1.insert('x'); s1.insert('y'); cout << "Size of set container s1 is : " << s1.size(); //移动构造函数 set<char> s2(move(s1)); cout << "\nSize of new set container s2 is : " << s2.size(); return 0; }
输出:
Size of set container s1 is : 2 Size of new set container s2 is : 2
在上面的示例中,s1的内容被移至s2 set。
让我们看一个简单的初始化列表构造函数:例子
#include <iostream> #include <set> #include <string> using namespace std; int main() { //初始化列表构造函数 set<string> fruit { "orange", "apple", "mango", "peach", "grape" }; cout << "Size of set container fruit is : " << fruit.size(); return 0; }
输出:
Size of set container fruit is : 5
上面的示例创建一个以字符串为键的set水果,并使用initializer_list对其进行初始化。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Tony Bai · Go语言第一课 -〔Tony Bai〕