您的位置:首页 > 其它

关于Map的应用实例

2017-12-14 12:07 441 查看
#include"stdafx.h"
#include<iostream>
#include<string>
#include<map>
using namespace std;

#if 0
map<string, int> m_map = { { "DBF", 1209 }, { "DAW", 1202 } };  //初始化赋值

typedef map<string, int>::iterator iter;

int main()
{

//m_map
m_map.insert(pair<string,int>("DF1", 1990));     //pair是一个模板类
m_map.insert(make_pair("DYW1", 1991));           //make_pair 返回的是一个pair对象
m_map.insert(map <string, int>::value_type("DG", 23));
m_map.insert(pair<string, int>("DD", 2990));
auto it = m_map.begin();
while (it != m_map.end())
{
cout <<it->first<<"="<< it->second << endl;
it++;
}

cout << "mapzie= " << m_map.size() << endl;

/*判断插入的是成功*/
pair<iter, bool> inPair;
inPair = m_map.insert(make_pair("DYW111", 1992));

if (inPair.second == true)
{
cout << "insert Suceed!" << endl;
}
else
{
cout << "inseret failed" << endl;
}

/*end*/

iter  it2 = m_map.find("DBF");
if (it2 != m_map.end())
{
cout << it2->second << endl;
}

iter it3 = m_map.lower_bound("DA"); //找到大于等于"DA"的迭代器
iter it4 = m_map.upper_bound("DF"); //找到大于"DF"的迭代器

/*删除map中多个数据*/
for (; it3 != it4; )
{
cout << "Data" << it3->second << endl;
iter itdel = it3;
it3++;
m_map.erase(itdel);
it4 = m_map.upper_bound("DF");
}

it = m_map.begin();
while (it != m_map.end())
{
cout << it->first << "=" << it->second << endl;
it++;
}

/*删除map中全部数据*/

m_map.erase(m_map.begin(), m_map.end());
cout << "mapzie= " << m_map.size() << endl;
system("pause");
}

#endif

typedef struct MyStruct
{
int nID;
string name;
bool operator<( const MyStruct &stru) const
{
return nID < stru.nID ? true : false;
}
}StuInfo;

map<StuInfo, int> m_stu;

int main2()
{
StuInfo s1 = { 16, "DF" };
StuInfo s2 = { 13, "DYW" };
/*s1.name = "DF";
s1.nID = 12;
s2.name = "DYW";
s2.nID = 13;*/
m_stu.insert(make_pair(s1, 300));
m_stu.insert(make_pair(s2, 200));

auto it = m_stu.begin();
while (it!= m_stu.end())
{
cout << (it->first).name<< endl;
it++;

}
cout << "hello<<endl" << endl;
system("pause");
return  0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: