1. 程式人生 > 其它 >資料結構(1) pair和map使用

資料結構(1) pair和map使用

#include <iostream>

#include <thread>

#include<map>

#include <algorithm>

#include <vector>

#ifdef lniux 
#include <unistd.h> //usleep(1000000);
#else
#include <Windows.h>
#include <WinBase.h>
#endif



using namespace std;




void test1_pair() {
	// pair測試
	typedef pair<string, string> Author;
	Author proust("March", "Proust");
	cout << "pair 測試  first:" << proust.first << "   second:  " << proust.second << endl;

}

void test1_insert() {

	//第一種:用insert函式插入pair資料:
	map<int, string> my_map;
	my_map.insert(pair<int, string>(1, "first"));
	my_map.insert(pair<int, string>(2, "second"));

	my_map.insert(map<int, string>::value_type(3, "2"));
	my_map.insert(map<int, string>::value_type(4, "3"));

	my_map[5] = "5";
	my_map[6] = "6";

	//std::cout << my_map[1] << endl;
	//std::cout << my_map[2] << endl;

	map<int, string>::iterator it;
	for (it = my_map.begin(); it != my_map.end(); it++)
		cout << "map測試 first:  " << it->first << " second: " << it->second << endl;




}

void test2_find() {

	//查詢 判斷關鍵字是否出現

	map< string, int> myfing_map;
	myfing_map.insert(pair<string, int>("dongdong", 21));
	myfing_map.insert(pair<string, int>("xixi", 22));
	myfing_map.insert(pair<string, int>("lala", 23));
	map<string, int>::iterator it1;
	it1 = myfing_map.find("dongdong");
	if (it1 != myfing_map.end())
		cout << "Find, the value is " << it1->second << endl;
	else
		cout << "Do not Find" << endl;

}

void test4_erase()
{
	map<int, string> my_map;
	my_map.insert(pair<int, string>(1, "one"));
	my_map.insert(pair<int, string>(2, "two"));
	my_map.insert(pair<int, string>(3, "three"));
	//如果你要演示輸出效果,請選擇以下的一種,你看到的效果會比較好
	//如果要刪除1,用迭代器刪除
	map<int, string>::iterator it;
	it = my_map.find(1);
	my_map.erase(it);                   //如果要刪除1,用關鍵字刪除
	int n = my_map.erase(1);            //如果刪除了會返回1,否則返回0
	//用迭代器,成片的刪除
	//一下程式碼把整個map清空
	my_map.erase(my_map.begin(), my_map.end());
	//成片刪除要注意的是,也是STL的特性,刪除區間是一個前閉後開的集合
	//自個加上遍歷程式碼,列印輸出吧
	
}




bool cmp(pair<string, int> a, pair<string, int> b) {
	return a.second < b.second;
}

void test3_sort() {

	// 排序
	map<string, int> ma;
	ma["Alice"] = 86;
	ma["Bob"] = 78;
	ma["Zip"] = 92;
	ma["Stdevn"] = 88;
	//vector< pair<string, int> > vec(ma.begin(), ma.end());

	vector< pair<string, int> > vec;
	for (map<string, int>::iterator it = ma.begin(); it != ma.end(); it++)
		vec.push_back(pair<string, int>(it->first, it->second));

	sort(vec.begin(), vec.end(), cmp);
	for (vector< pair<string, int> >::iterator it = vec.begin(); it != vec.end(); ++it)
	{
		cout << it->first << " " << it->second << endl;

	}


}



int main(int argc, char** argv)
{

	test1_pair();
	test1_insert();
	test2_find();
	test3_sort();
	test4_erase();

}