// 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;
}
STL学习(一)map容器学习
最新推荐文章于 2023-08-04 17:43:32 发布