您的位置:首页 > 其它

STL 中容器 map 的使用

2013-06-25 10:24 447 查看
以下代码实现stl中容器 map 的简单操作。包括插入,更新,遍历,查找。

 

#pragma once

#include "string"
#include "iostream"
#include "map"

using namespace std;

class CStudent
{
string name;
int english;
public:
CStudent(void);
~CStudent(void);
CStudent(string name, int english);
public:
void inline printit()
{
cout<<"name=";
cout<<name;
cout<<"   english=";
cout<<english;
cout<<endl;
}
};

#include "stdafx.h"
#include "Student.h"

CStudent::CStudent(void)
{
}

CStudent::CStudent(string name, int english)
{
this->name = name;
this->english = english;
}

CStudent::~CStudent(void)
{
}


 

#pragma once

#include "Student.h"
#include "map"

using namespace std;

class CStudentMap
{
public:
CStudentMap(void);
~CStudentMap(void);
private:
map<int, CStudent> m_studentmap;
public:
bool insert(int number, CStudent stu);
bool remove(int number);
bool update(int number, CStudent stu);
bool find(int number, CStudent& stu);
void output();
int  count();

};

#include "stdafx.h"
#include "StudentMap.h"
#include "algorithm"

CStudentMap::CStudentMap(void)
{
}

CStudentMap::~CStudentMap(void)
{
}

int  CStudentMap::count()
{
return m_studentmap.size();
}

bool CStudentMap::insert(int number, CStudent stu)
{
pair<map<int, CStudent>::iterator, bool> Insert_Pair;
Insert_Pair = m_studentmap.insert(pair<int, CStudent>(number, stu));
if(Insert_Pair.second)
{
return true;
}
else
{
return false;
}

/*Insert_Pair = m_studentmap.insert(map<int, CStudent>::value_type(number, stu));
if(Insert_Pair.second == true)
{
return true;
}
else
{
return false;
}*/

}

bool CStudentMap::remove(int number)
{
map<int, CStudent>::iterator LI;
LI = m_studentmap.find(number);
if (LI != m_studentmap.end())
{
m_studentmap.erase(LI);
return true;
}
else
{
return false;
}
}

bool CStudentMap::update(int number, CStudent stu)
{
m_studentmap[number] = stu;
return true;
}

void CStudentMap::output()
{
map<int, CStudent>::iterator LI;
for(LI = m_studentmap.begin(); LI != m_studentmap.end(); LI++)
{
LI->second.printit();
}
}

bool CStudentMap::find(int number, CStudent &stu)
{
map<int, CStudent>::iterator LI;
LI = m_studentmap.find(number);
if (LI != m_studentmap.end())
{
stu = (LI)->second;
return true;
}
else
{
return false;
}
}


以下为主函数测试:

 

// stlmap.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "StudentMap.h"

int _tmain(int argc, _TCHAR* argv[])
{

CStudentMap smap;

CStudent stu[10];
for(int i=0; i<10; i++)
{
char buff[100];
sprintf_s(buff, 100 ,"zhang%02d",i);
string name(buff);
CStudent student(name, i*10);
stu[i] = student;
smap.insert(i, stu[i]);
}
smap.output();

bool ret1 = smap.insert(0, stu[0]);

bool ret = smap.find(15, stu[8]);
cout<<"************************"<<endl;
if (ret)
{
stu[8].printit();
}
else
{
cout<<"not find"<<endl;
}

system("pause");
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: