linux下练习 c++ 关联式容器map特性
/*map.cppmap特性不允许key重复key/value对key可以当下标访问value,key不存在则插入新的key/value对,以0初始化*/#include#include#include "print.h"#includeusing namespace std;typedef pairpairmp;#includeint main
·
/*
map.cpp
map特性
不允许key重复
key/value对
key可以当下标访问value,key不存在则插入新的key/value对,以0初始化
*/
#include<iostream>
#include<string>
#include "print.h"
#include<map>
using namespace std;
typedef pair<int,string> pairmp;
#include<map>
int main()
{
map<int,string> mp;
mp.insert(pair<int,string>(1,"aaa"));
mp.insert(make_pair(5,"bbb"));//自动匹配类型,构造pair
mp.insert(map<int,string>::value_type(4,"fff"));//内部类型,也能自动构造相应的pair
mp.insert(make_pair(2,"hhh"));
mp.insert(make_pair(2,"hhh"));
mp[2]="hhh1";//有则修改
mp[3]="ddd";//无则插入
print(mp.begin(),mp.end());
return 0;
}
print.h
//print.h
#include <iostream>
using namespace std;
#ifndef print_fun
#define print_fun
template<typename T>
///显示序列数据
void print(T b,T e,char c=' ')
{
bool isExit=false;
while (b!=e)
{
cout<<*b++<<c;
isExit=true;
}
if(isExit) cout<<endl;
}
template<typename K,typename V>
ostream& operator<<(ostream& o,const pair<K,V>& p)//重载输出map类型元素
{
return o<<p.first<<':'<<p.second;
}
#endif
#include<iostream>
using namespace std;
#include<fstream>
#include<map>
#include<cstring>
class Candidate{
public:
Candidate(const string& name=""):m_name(name),m_votes(0){}
Candidate(const char* name):m_name(name),m_votes(0){}
const string& name() const{
return m_name;
}
const int& votes() const{
return m_votes;
}
void vote(){
++ m_votes;
}
private:
string m_name;
int m_votes;
};
//测试投票
void test1(){
map<char,Candidate> mcc;
mcc.insert(make_pair('a',Candidate("zhangsan")));
mcc.insert(pair<char,Candidate>('f',"zhaoyun"));
mcc['b']=Candidate("lisi");
typedef map<char,Candidate>::iterator IT;
typedef map<char,Candidate>::const_iterator CIT;
for(int i=0;i<5;i++)
{
for(CIT it=mcc.begin();it!=mcc.end();it++)
{
//it->second.vote();
cout<<it->first<<":"<<it->second.name()<<" ";
}
cout<<endl<<"请投票:";
char key;
cin>>key;
IT fit=mcc.find(key);
if(fit==mcc.end()) continue;
fit->second.vote();
cout<<"投了一票给"<<fit->first<<endl;
}
CIT win=mcc.begin();
for(CIT it=mcc.begin();it!=mcc.end();it++){
cout<<it->second.name()<<":"
<<it->second.votes()<<endl;
if(it->second.votes()>win->second.votes()) win=it;
}
cout<<"最多票数:"<<win->second.name()<<endl;
}
class StrCmp{//让字符串大小写不区分
public:
bool operator()(const string& a,const string& b){
return strcasecmp(a.c_str(),b.c_str())<0;
}
bool operator()(const char* a,const char* b){
return strcasecmp(a,b)<0;
}
};
//统计每个单词出现的次数
void test2()
{
ifstream ifs("words.txt");
map<string,int,StrCmp> msi;
string word;
while(ifs>>word) msi[word]++;
ifs.close();
typedef map<string,int>::iterator IT;
cout<<"一共"<<msi.size()<<"个单词"<<endl;
for(IT it=msi.begin();it!=msi.end();it++)
{
cout<<it->first<<":"<<it->second<<"\n";
}
}
int main()
{
//test1();
test2();
return 0;
}
更多推荐
已为社区贡献2条内容
所有评论(0)