📅  最后修改于: 2023-12-03 15:13:56.561000             🧑  作者: Mango
在C++ STL中,multimap是一种存储键值对的数据容器,其中键可以重复。multimap中提供了swap()方法,用于交换两个multimap容器的内容。
multimap1.swap(multimap2);
无返回值。
#include <iostream>
#include <map>
using namespace std;
int main() {
multimap<int, string> mm1 = {{1, "a"}, {2, "b"}, {3, "c"}};
multimap<int, string> mm2 = {{4, "d"}, {5, "e"}, {6, "f"}};
cout << "Before swapping:" << endl;
for (auto it = mm1.begin(); it != mm1.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
for (auto it = mm2.begin(); it != mm2.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
mm1.swap(mm2);
cout << "After swapping:" << endl;
for (auto it = mm1.begin(); it != mm1.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
for (auto it = mm2.begin(); it != mm2.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
输出:
Before swapping:
1: a
2: b
3: c
4: d
5: e
6: f
After swapping:
4: d
5: e
6: f
1: a
2: b
3: c
在上述示例中,我们首先创建了两个multimap容器mm1和mm2,并将它们分别初始化为{{1, "a"}, {2, "b"}, {3, "c"}}和{{4, "d"}, {5, "e"}, {6, "f"}}。然后我们使用swap()方法将它们的内容交换。最后,我们遍历两个multimap容器,分别输出它们的键和值,以验证内容是否被成功交换。
需要注意的是,swap()方法只交换multimap容器的内容,而不会改变multimap容器的大小或容量。