添加元素
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle.insert(std::pair<int,std::string>(1,"hello"));
return 0;
}
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle.insert(std::map<int,std::string>::value_type(1,"hello"));
return 0;
}
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle[1] = "hello";
return 0;
}
遍历元素
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle[1] = "hello";
mapEle[2] = "world";
mapEle[3] = "你好";
mapEle[4] = "世界";
for (auto iter = mapEle.begin(); iter != mapEle.end(); iter++)
{
int nKey = iter->first;
std::string strValue = iter->second;
}
return 0;
}
删除元素
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle[1] = "hello";
mapEle[2] = "world";
mapEle[3] = "你好";
mapEle[4] = "世界";
auto iter = mapEle.erase(mapEle.begin());
return 0;
}
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle[1] = "hello";
mapEle[2] = "world";
mapEle[3] = "你好";
mapEle[4] = "世界";
int n = mapEle.erase(2);
return 0;
}
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle[1] = "hello";
mapEle[2] = "world";
mapEle[3] = "你好";
mapEle[4] = "世界";
auto iter = mapEle.erase(mapEle.begin(),mapEle.end());
return 0;
}
查找元素
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle[1] = "hello";
mapEle[2] = "world";
mapEle[3] = "你好";
mapEle[4] = "世界";
auto iter = mapEle.find(2);
if (iter != mapEle.end())
{
int nKey = iter->first;
std::string strValue = iter->second;
}
else
std::cout << "不存在" << std::endl;
return 0;
}
判断元素是否存在
#include <iostream>
#include <map>
#include <string>
int main(int argc, char **argv)
{
std::map<int, std::string> mapEle;
mapEle[1] = "hello";
mapEle[2] = "world";
mapEle[3] = "你好";
mapEle[4] = "世界";
bool bRt = mapEle.count(2);
if (bRt)
std::cout << "存在" << std::endl;
else
std::cout << "不存在" << std::endl;
return 0;
}