map在以下三種情況下使用operator =():
Operator =()用于通過(guò)替換舊內(nèi)容(或復(fù)制內(nèi)容)將新內(nèi)容分配給map容器,并在必要時(shí)修改大小。
Operator =()用于將一個(gè)map容器的內(nèi)容移至另一個(gè),并在必要時(shí)修改大小。
Operator =用于將元素從初始化列表復(fù)制到map容器。
copy(1) map& operator= (const map& x); // 在 C++ 11 之前 copy (1) map& operator= (const map& x); //從 C++ 11 開(kāi)始 move (2) map& operator= (map&& x); //從 C++ 11 開(kāi)始 initializer list (3) map& operator= (initializer_list<value_type> il); //從 C++ 11 開(kāi)始
copy(1):- 將x中的所有元素復(fù)制到map容器中。
move(2):- 將x的內(nèi)容移動(dòng)到map容器中。
initializer_list(3):- 將il的元素復(fù)制到map容器中。
x:具有相同類(lèi)型的map對(duì)象。
il:初始化列表對(duì)象。
這個(gè)指針。
讓我們看一個(gè)簡(jiǎn)單的示例,將一個(gè)map的內(nèi)容復(fù)制到另一個(gè)map。
#include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m1 = { {'a', 10}, {'b', 20}, {'c', 30} }; cout << "Map m1包含以下元素" << endl; for (auto it = m1.begin(); it != m1.end(); ++it) cout << it->first << " = " << it->second << endl; map<char, int> m2 = m1; cout<<"\n將元素從m1復(fù)制到m2之后... \n"; cout << "\nMap m2包含以下元素" << endl; for (auto it = m2.begin(); it != m2.end(); ++it) cout << it->first << " = " << it->second << endl; return 0; }
輸出:
Map m1包含以下元素 a = 10 b = 20 c = 30 將元素從m1復(fù)制到m2之后... Map m2包含以下元素 a = 10 b = 20 c = 30
在上面的示例中,使用operator =()函數(shù)將一個(gè)Map m1的內(nèi)容復(fù)制到另一個(gè)Map m2。
讓我們看一個(gè)簡(jiǎn)單的示例,將一個(gè)map的元素移動(dòng)到另一個(gè)。
#include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m1 = { {'a', 1}, {'b', 2}, {'c', 3} }; cout << "Map m1包含以下元素" << endl; for (auto it = m1.begin(); it != m1.end(); ++it) cout << it->first << " = " << it->second << endl; map<char, int> m2 = move(m1); cout<<"\n將元素從m1移到m2后... \n"; cout << "\nMap m2包含以下元素" << endl; for (auto it = m2.begin(); it != m2.end(); ++it) cout << it->first << " = " << it->second << endl; return 0; }
輸出:
Map m1包含以下元素 a = 1 b = 2 c = 3 將元素從m1移到m2后... Map m2包含以下元素 a = 1 b = 2 c = 3
在上面的示例中,使用operator =()函數(shù)將一個(gè)map m1的內(nèi)容移動(dòng)到另一map m2。
讓我們看一個(gè)簡(jiǎn)單的示例,將初始化列表中的內(nèi)容復(fù)制到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包含以下元素" << endl; for (auto it = m.begin(); it != m.end(); ++it) cout << it->first << " = " << it->second << endl; return 0; }
輸出:
Map包含以下元素 a = 100 b = 200 c = 300 d = 400
在上面的示例中,operator =()用于將內(nèi)容從初始化列表復(fù)制到Map m。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例。
#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; // second 現(xiàn)在包含整數(shù) first=map<char,int>(); // first現(xiàn)在是空 cout << "Size of first: " << first.size() << '\n'; cout << "Size of second: " << second.size() << '\n'; return 0; }
輸出:
Size of first: 0 Size of second: 3
在上面的示例中,首先它將計(jì)算空Map fisrt的大小,然后將一些元素添加到第一個(gè)Map 并復(fù)制到第二個(gè)Map。