C++ 把一个枚举作为Key录入map
时间: 2024-01-25 19:04:25 浏览: 19
可以这样做,枚举类型可以作为map的key,例如:
```
#include <iostream>
#include <map>
using namespace std;
enum Fruit {
Apple,
Orange,
Banana
};
int main() {
map<Fruit, int> fruitCount;
fruitCount[Apple] = 5;
fruitCount[Orange] = 3;
fruitCount[Banana] = 2;
cout << "Number of apples: " << fruitCount[Apple] << endl;
return 0;
}
```
输出结果为:
```
Number of apples: 5
```
请问还有其它问题吗?
相关问题
c++中枚举值可以作为map的value吗?
可以,枚举值可以作为map的value。在C++中,枚举类型被视为整数类型,所以它们可以用作map的值类型。在使用枚举值作为map的值时,需要注意枚举类型的值必须可以转换为map的键类型。例如,如果map的键类型是int类型,那么枚举类型的值必须是可以转换为int类型的值。以下是一个示例代码:
```c++
#include <iostream>
#include <map>
enum class Color {
Red,
Green,
Blue
};
int main() {
std::map<int, Color> colors{{1, Color::Red}, {2, Color::Green}, {3, Color::Blue}};
for (const auto& [key, value] : colors) {
std::cout << "Key: " << key << ", Value: " << static_cast<int>(value) << std::endl;
}
return 0;
}
```
在上面的示例代码中,我们定义了一个枚举类型Color,并将其作为map的值类型。我们还创建了一个名为colors的map,其中键类型为int,值类型为Color。我们将三个键值对添加到map中,并使用循环输出每个键值对的键和值。请注意,我们在输出值时使用了static_cast将枚举值转换为int类型。
C++map一个key对应多个value
在C语言中,可以使用结构体和链表来实现一个key对应多个value的映射结构。具体实现方式如下:
1. 定义一个结构体,包含一个key和一个指向链表头节点的指针。
```c
typedef struct Node {
int key;
struct ValueNode *head;
} Node;
```
2. 定义一个用于存储value的结构体。
```c
typedef struct ValueNode {
int value;
struct ValueNode *next;
} ValueNode;
```
3. 定义一个哈希表,用于存储所有的Node节点。
```c
#define MAX_SIZE 100000
Node hashTable[MAX_SIZE];
int hash(int key) {
return key % MAX_SIZE;
}
```
4. 实现一个添加key-value对的函数。
```c
void add(int key, int value) {
int index = hash(key);
Node *node = &hashTable[index];
while (node->key != key && node->head != NULL) {
node = node->head;
}
if (node->key != key) {
node->key = key;
node->head = (ValueNode*)malloc(sizeof(ValueNode));
node->head->value = value;
node->head->next = NULL;
} else {
ValueNode *cur = node->head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = (ValueNode*)malloc(sizeof(ValueNode));
cur->next->value = value;
cur->next->next = NULL;
}
}
```
5. 实现一个查询key对应的所有value的函数。
```c
ValueNode* find(int key) {
int index = hash(key);
Node *node = &hashTable[index];
while (node != NULL) {
if (node->key == key) {
return node->head;
}
node = node->head;
}
return NULL;
}
```
使用示例:
```c
add(1, 2);
add(1, 3);
add(2, 4);
ValueNode *values = find(1);
while (values != NULL) {
printf("%d ", values->value);
values = values->next;
}
// Output: 2 3
```