string 转 map
时间: 2023-09-03 08:06:38 浏览: 58
你可以使用以下代码将一个字符串转换为map:
```cpp
#include <iostream>
#include <map>
#include <sstream>
std::map<std::string, std::string> stringToMap(const std::string& str) {
std::map<std::string, std::string> result;
std::stringstream ss(str);
std::string key, value;
while (std::getline(ss, key, '=')) {
if (std::getline(ss, value, '&')) {
result[key] = value;
}
}
return result;
}
int main() {
std::string str = "key1=value1&key2=value2&key3=value3";
std::map<std::string, std::string> myMap = stringToMap(str);
for (const auto& pair : myMap) {
std::cout << pair.first << " : " << pair.second << std::endl;
}
return 0;
}
```
这段代码将字符串`"key1=value1&key2=value2&key3=value3"`转换为一个包含键值对的map。输出结果将为:
```
key1 : value1
key2 : value2
key3 : value3
```
你可以根据实际的字符串格式和需求进行修改。