map在以下三种情况下使用operator =():
Operator =()用于通过替换旧内容(或复制内容)将新内容分配给map容器,并在必要时修改大小。
Operator =()用于将一个map容器的内容移至另一个,并在必要时修改大小。
Operator =用于将元素从初始化列表复制到map容器。
copy(1) map& operator= (const map& x); // 在 C++ 11 之前 copy (1) map& operator= (const map& x); //从 C++ 11 开始 move (2) map& operator= (map&& x); //从 C++ 11 开始 initializer list (3) map& operator= (initializer_list<value_type> il); //从 C++ 11 开始
copy(1):- 将x中的所有元素复制到map容器中。
move(2):- 将x的内容移动到map容器中。
initializer_list(3):- 将il的元素复制到map容器中。
x:具有相同类型的map对象。
il:初始化列表对象。
这个指针。
让我们看一个简单的示例,将一个map的内容复制到另一个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复制到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复制到m2之后... Map m2包含以下元素 a = 10 b = 20 c = 30
在上面的示例中,使用operator =()函数将一个Map m1的内容复制到另一个Map m2。
让我们看一个简单的示例,将一个map的元素移动到另一个。
#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 =()函数将一个map m1的内容移动到另一map 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包含以下元素" << 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 =()用于将内容从初始化列表复制到Map 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; // second 现在包含整数
first=map<char,int>(); // first现在是空
cout << "Size of first: " << first.size() << '\n';
cout << "Size of second: " << second.size() << '\n';
return 0;
}输出:
Size of first: 0 Size of second: 3
在上面的示例中,首先它将计算空Map fisrt的大小,然后将一些元素添加到第一个Map 并复制到第二个Map。