STL學習(一)map容器學習

// test_STL.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include<iostream>
#include <map>
#include <string>
#include <utility>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	cout << "enchanter: " <<endl;
     /*constructor-1*/
    map<string,int> word_count;


	/*insert-1*/
	word_count["strength"] = 100;
	cout << "strength: " << word_count["strength"] <<endl;


	/*insert-2*/
	pair<string ,int> enchanter("magic point",500);
	pair<map<string,int>::iterator,bool> result;
	result = word_count.insert(enchanter);
	cout << "magic point: " << word_count["magic point"] <<" bool: "<<result.second<<endl;
	cout << "iterator:value first : "<< result.first->first<<endl;
	cout << "iterator:value second : "<< result.first->second<<endl;

	/*insert-3*/
	word_count.insert(make_pair(string("defense"),50));
	//word_count.insert(make_pair("defense",50)); in VS2010,it's ok.in VC6,it's wrong
	cout << "defense: " << word_count["defense"] <<endl;
	/*bug fix:
	word_count.insert(make_pair("defense",50));
	編譯器把coll.insert(make_pair("defense",1));中的"defense"認成const char[]類型了,
	與make_pair(string,string)不匹配
	修改爲:word_count.insert(make_pair(string("defense"),50));
	*/
    
    cout <<endl;
    cout << "female_enchanter: " <<endl;
    /*constructor-2*/
	map<string,int> female_enchanter(word_count);


	map<string,int>::iterator map_it = female_enchanter.begin();
	while(map_it != female_enchanter.end())
	{
		cout<<map_it->first<<" : "<<map_it->second<< endl;
		++map_it;
	}
	/*bug fix:
	error C2679: binary '<<' : no operator defined which takes a right-hand operand 
	of type 'const class std::basic_string<char,struct std::char_traits<char>,class 
	std::all
	將#include<iostream.h> 修改爲#include<iostream>
	*/
	
	map<string,int>::const_iterator map_begin = female_enchanter.begin();
	map<string,int>::const_iterator map_end = female_enchanter.end();


    cout <<endl;
    cout << "Sorcerer_Apprentice: " <<endl;

     /*constructor-3*/
	map<string,int> Sorcerer_Apprentice(map_begin, map_end);

	
	map<string,int>::iterator map_iterator = Sorcerer_Apprentice.begin();

	while(map_iterator != Sorcerer_Apprentice.end())
	{
		cout<<map_iterator->first<<" : "<<map_iterator->second<< endl;
		++map_iterator;
	}

	/*count return 1:exist.0:not exist*/
	string str1 = "drunken brawler";
	if(Sorcerer_Apprentice.count(str1))
	{
		cout << str1 << "is exist in Sorcerer_Apprentice"<< endl;
	}
	else
	{
		cout << str1 << "is not exist in Sorcerer_Apprentice"<< endl;
	}

	/*find*/
	string str2 = "defense";
	if(Sorcerer_Apprentice.find(str2) != Sorcerer_Apprentice.end())
	{
		cout << str2 << " is exist in Sorcerer_Apprentice"<< endl;
	}
	else
	{
		cout << str2 << " is not exist in Sorcerer_Apprentice"<< endl;
	}



	system("Pause");
	
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章