set中有operator=的以下三种用法:
copy(1) set& operator= (const set& x); //until C++ 11 copy (1) set& operator= (const set& x); //since C++ 11 move (2) set& operator= (set&& x); //since C++ 11 initializer list (3) set& operator= (initializer_list<value_type> il); //since C++ 11
copy (1): - 将x中的所有元素复制到集合集合中。
move (2): - 将x的内容移动到set集合中。
initializer_list (3):- 将il的元素复制到set集合中。
x - 具有相同类型的集合对象。
il - 初始化列表对象。
返回*this 指针。
让我们看一个简单的示例,将一组内容复制到另一组:
#include <iostream> #include <set> using namespace std; int main(void) { set<int> s1 = {10,20,30}; cout << "Set s1 contains following elements" << endl; for (auto it = s1.begin(); it != s1.end(); ++it) cout << *it << endl; set<int> s2 = s1; cout<<"\nAfter Copying the elements from s1 to s2... \n"; cout << "\nSet s2 contains following elements" << endl; for (auto it = s2.begin(); it != s2.end(); ++it) cout << *it<< endl; return 0; }
输出:
Set s1 contains following elements 10 20 30 After copying the elements from s1 to s2... Set s2 contains following elements 10 20 30
在上面的示例中,运算符=用于将一个集合s1的内容复制到另一集合s2。
让我们看一个简单的示例,将一组元素移到另一组:
#include <iostream> #include <set> using namespace std; int main(void) { set<char> s1 = {'a','e','i','o','u'}; cout << "Set m1 contains following elements" << endl; for (auto it = s1.begin(); it != s1.end(); ++it) cout << *it << ", "; set<char> s2 = move(s1); cout<<"\n\nAfter moving the elements from s1 to s2... \n"; cout << "\nSet s2 contains following elements" << endl; for (auto it = s2.begin(); it != s2.end(); ++it) cout << *it << ", "; return 0; }
输出:
Set m1 contains following elements a, e, i, o, u, After moving the elements from s1 to s2? Set s2 contains following elements a, e, i, o, u,
在上面的示例中,运算符=用于将一个集合s1的内容移动到另一集合s2。
让我们看一个简单的示例,从初始化列表复制内容以进行设置:
#include <iostream> #include <set> using namespace std; int main(void) { set<int> s; s = {100, 200, 300, 400, 500}; //initializer list cout << "Set contains the following elements" << endl; for (auto it = s.begin(); it != s.end(); ++it) cout << *it << endl; return 0; }
输出:
Set contains the following elements 100 200 300 400 500
在上面的示例中,operator =用于复制初始化程序列表中的内容以设置m。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-operator=.html
来源:LearnFk无涯教程网
让我们看一个简单的例子:
#include <iostream> #include <set> using namespace std; int main () { int values [] = { 5 , 2 , 4 , 1 , 0 , 0 , 9 }; set < int > c1 ( values , values + 7 ); set < int > c2 ; c2 = c1 ; c1 = set < int > (); cout<< "Size Of c1:" << c1 . size () << endl ; cout<< "Size Of c2:" << c2 . size () << endl ; }
输出:
Size Of c1:0 Size Of c2:6
在上面的示例中,有两组c1和c2。 c1有7个元素,c2为空,但是将c1分配给c2后,c1的大小变为0,c2的大小变为7。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)