写一个std::map<std::string, std::variant<int, std::string>>赋值并读取的demo
时间: 2024-06-24 12:02:19 浏览: 8
当使用`std::map`结合`std::variant`在C++中存储键值对时,你可以创建一个映射,其中键是`std::string`类型,值是一个可以是`int`或`std::string`类型的`std::variant`。以下是一个简单的示例,展示如何创建、添加、访问和读取这些数据:
```cpp
#include <iostream>
#include <map>
#include <variant>
#include <string>
using Value = std::variant<int, std::string>;
// 创建一个std::map实例
std::map<std::string, Value> myMap;
// 添加元素
void addElement(const std::string& key, int intValue) {
myMap[key] = intValue;
std::cout << "Added " << key << " with int value: " << intValue << std::endl;
}
void addElement(const std::string& key, const std::string& stringValue) {
myMap[key] = stringValue;
std::cout << "Added " << key << " with string value: " << stringValue << std::endl;
}
// 读取元素(假设值是int)
int getValueAsInt(const std::string& key) {
auto it = myMap.find(key);
if (it != myMap.end()) {
return std::get<int>(*it->second);
}
throw std::runtime_error("Key not found in the map");
}
// 读取元素(假设值是std::string)
std::string getValueAsString(const std::string& key) {
auto it = myMap.find(key);
if (it != myMap.end()) {
return std::get<std::string>(*it->second);
}
throw std::runtime_error("Key not found in the map");
}
int main() {
// 示例用法
addElement("key1", 100);
addElement("key2", "Hello");
// 读取并输出int值
try {
std::cout << "Value of key1 as int: " << getValueAsInt("key1") << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
// 读取并输出string值
try {
std::cout << "Value of key2 as string: " << getValueAsString("key2") << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
```
在这个例子中,`addElement`函数用于向map中添加元素,`getValueAsInt`和`getValueAsString`分别用于根据键获取对应的整数或字符串值。注意,由于`std::variant`的值可能包含不同类型的值,因此在读取时需要指定类型进行解包。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)