1. 程式人生 > 其它 >C++map容器-大小和互換

C++map容器-大小和互換

技術標籤:C++基礎學習c++資料結構

map大小和互換
功能描述:
統計map容器大小以及交換map容器

函式原型:
在這裡插入圖片描述

程式碼如下:

#include <iostream>
using namespace std;
#include <map>

//map容器  大小和交換
void test01() {
	map<int, int>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>
(3, 30)); if (m.empty()) { cout << "m為空" << endl; } else { cout << "m不為空" << endl; cout << "m的大小為:" << m.size() << endl; } } void printMap(map<int, int> &m) { for (map<int, int>::iterator it = m.begin
(); it != m.end(); it++) { cout << "key = " << it->first << " " << "value = " << it->second << endl; } cout << endl; } void test02() { map<int, int>m1; m1.insert(pair<int, int>(1, 10)); m1.insert(pair<
int, int>(2, 20)); m1.insert(pair<int, int>(3, 30)); map<int, int>m2; m2.insert(pair<int, int>(4, 100)); m2.insert(pair<int, int>(5, 200)); m2.insert(pair<int, int>(6, 300)); cout << "交換前:" << endl; printMap(m1); printMap(m2); cout << "交換後:" << endl; m1.swap(m2); printMap(m1); printMap(m2); } int main() { test01(); cout << "----------------------" << endl; test02(); return 0; }