映射中有以下三种使用operator =()的方式:
copy(1) map& operator= (const map& x); //until C++ 11 copy (1) map& operator= (const map& x); //since C++ 11 move (2) map& operator= (map&& x); //since C++ 11 initializer list (3) map& operator= (initializer_list<value_type> il); //since C++ 11
copy(1) :- 将x中的所有元素复制到映射集合中。
copy(2) :- 将x的内容移动到映射集合中。
initializer_list(3) :- 将il的元素复制到映射集合中。
x : 具有相同类型的映射对象。
il : 初始化列表对象。
这个*this指针。
让我们看一个简单的示例,将一个映射的内容复制到另一个映射。
#include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m1 = { {'a', 10}, {'b', 20}, {'c', 30} }; cout << "Map m1 contains following elements" << endl; for (auto it = m1.begin(); it != m1.end(); ++it) cout << it->first << " = " << it->second << endl; map<char, int> m2 = m1; cout<<"\nAfter Copying the elements from m1 to m2... \n"; cout << "\nMap m2 contains following elements" << endl; for (auto it = m2.begin(); it != m2.end(); ++it) cout << it->first << " = " << it->second << endl; return 0; }
输出:
Map m1 contains following elements a = 10 b = 20 c = 30 After copying the elements from m1 to m2... Map m2 contains following elements a = 10 b = 20 c = 30
在上面的示例中,使用operator =()函数将一个映射图m1的内容复制到另一个映射图m2。
让我们看一个简单的示例,将一个映射的元素移动到另一个。
#include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m1 = { {'a', 1}, {'b', 2}, {'c', 3} }; cout << "Map m1 contains following elements" << endl; for (auto it = m1.begin(); it != m1.end(); ++it) cout << it->first << " = " << it->second << endl; map<char, int> m2 = move(m1); cout<<"\nAfter moving the elements from m1 to m2... \n"; cout << "\nMap m2 contains following elements" << endl; for (auto it = m2.begin(); it != m2.end(); ++it) cout << it->first << " = " << it->second << endl; return 0; }
输出:
Map m1 contains following elements a = 1 b = 2 c = 3 After moving the elements from m1 to m2... Map m2 contains following elements a = 1 b = 2 c = 3
在上面的示例中,使用operator =()函数将一个映射m1的内容移动到另一映射m2。
让我们看一个简单的示例,将初始化列表中的内容复制到map。
#include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m; m = { {'a', 100}, {'b', 200}, {'c', 300}, {'d', 400} }; cout << "Map contains the following elements" << endl; for (auto it = m.begin(); it != m.end(); ++it) cout << it->first << " = " << it->second << endl; return 0; }
输出:
Map contains the following elements a = 100 b = 200 c = 300 d = 400
在上面的示例中,operator =()用于将内容从初始化列表复制到映射m。
让我们看一个简单的例子。
#include <iostream> #include <map> using namespace std; int main () { map<char,int> first; map<char,int> second; first['x']=8; first['y']=16; first['z']=32; second=first; //第二个现在包含 3 个整数 first=map<char,int>(); //第一个现在是空的 cout << "Size of first: " << first.size() << '\n'; cout << "Size of second: " << second.size() << '\n'; return 0; }
输出:
Size of first: 0 Size of second: 3
在上面的示例中,首先它将计算空图的大小,然后将一些元素添加到第一张图并复制到第二张图。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)