具有char*键和int值的容器
Container with char* key and int value
我需要一个可以存储char*
键和int
值的容器。
我可以使用std::map
和mfc CMap
,但当使用char*
作为键时,我不知道一些操作。
如下所示:
#include"iostream"
#include<map>
using namespace std;
std::map<char*,int>Mymap;
or
//Cmap<char*, char*, int, int>Mymap;
char* p = "AAA";
char* q = "BBB";
int p_val = 10;
int q_val = 20;
int main()
{
// How to use insert, find and access keys
return 0;
}
我想知道map
和CMap
的解
下面是如何使用std"映射char* key和int value的示例。
//Example of std::map with char* key and int as value.
#include"iostream"
using namespace std;
#include<map>
struct cmp_str
{
bool operator()(char *first, char *second)
{
return strcmp(first, second) < 0;
}
};
typedef std::map<char*,int, cmp_str>MAP;
MAP myMap;
void Search(char *Key)
{
MAP::iterator iter = myMap.find(Key);
if (iter != myMap.end())
{
cout<<"Key : "<<(*iter).first<<" found whith value : "<<(*iter).second<<endl;
}
else
{
cout<<"Key does not found"<<endl;
}
}
int main()
{
char *Key1 = "DEV";
char *Key2 = "TEST";
char *Key3 = "dev";
//Insert Key in Map
myMap.insert(MAP::value_type(Key1, 100));
myMap.insert(MAP::value_type(Key2, 200));
// Find Key in Map
Search(Key1); // Present in Map
Search(Key2); // Present in Map
Search(Key3); // Not in Map as it's case sensitive
myMap.erase(Key2); // Delete Key2
Search(Key2); // Not in Map as deleted
return 0;
}
通过使用MFC cmap,我们也可以实现相同的,但操作(函数)可能会改变。
请注意,如果您不编写自己的比较器,则内部映射函数实际比较的东西是char*元素的内存地址。你需要自己的比较器,这并不难写。或者简单地使用std::string
作为键,当您需要char*
时,只需调用string.c_str()
。
相关文章:
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- C ++如何在使用"tolower"时将char转换为int
- 在标准中,模板参数的语法在哪里定义,例如,'std::function<int(char)>'?
- 类型为 'std::map< char,int > 的 <Swig 对象的代理
- 声明具有两种类型的变量:"int char"
- 定义.cpp中常数int/char*
- Qt5 对'QApplication::QApplication(int&, char**, int)'的未定义引用
- 将int/char插入数据库
- 从 std::vector 转换为<int> char[] C++
- 为什么INT(char)的比较不起作用
- 使用int+char组合uint8_t
- 为什么这个返回值?C++int/char混淆
- 向量到 int<char> 与向量<wchar_t>到 int
- Evaluate an int, char and int
- 接收错误"no matching function for call to 'getline(std::ifstream&, int&, char)'"
- reinterpret_cast<int*>(char*) vs. static_cast<int*>(static_cast<void*>(char*)) --
- 将类型int(C::*)(int, char)转换为类型int(int, char)
- 如何添加多位数的int和char,其中输出为int+char
- 是int, char也是抽象数据类型