能否不使用qmap 而是map
时间: 2023-07-28 14:46:27 浏览: 136
可以的,你可以使用STL库中的std::map来替换QMap。下面是一个使用std::map来存储并以二进制格式写入文件的示例:
```c++
#include <map>
#include <fstream>
int main()
{
std::map<std::string, int> map;
map.insert({"apple", 1});
map.insert({"banana", 2});
map.insert({"orange", 3});
std::ofstream file("data.bin", std::ios::binary);
if (file.is_open()) {
file.write(reinterpret_cast<const char*>(&map), sizeof(map));
file.close();
}
return 0;
}
```
在上面的代码中,我们创建了一个std::map对象,并向其中插入了一些数据。然后我们创建了一个std::ofstream对象,并以二进制文件模式打开它。接着,我们将map对象的地址强制转换为const char*类型,并使用std::ofstream的write函数将其写入到文件中。
如果需要读取该文件中的Map对象,可以使用std::ifstream的read函数来读取。需要注意的是,在读取Map对象之前,必须先将std::map的实例化对象map定义出来。以下是读取二进制文件并还原Map对象的示例代码:
```c++
#include <map>
#include <fstream>
int main()
{
std::map<std::string, int> map;
std::ifstream file("data.bin", std::ios::binary);
if (file.is_open()) {
file.read(reinterpret_cast<char*>(&map), sizeof(map));
file.close();
}
// 输出Map对象中的元素
for (const auto& item : map) {
std::cout << item.first << ": " << item.second << std::endl;
}
return 0;
}
```
在上面的代码中,我们先创建一个空的std::map对象。然后我们打开之前写入的二进制文件,并使用std::ifstream的read函数读取Map对象。最后,我们遍历Map对象中的元素,并输出它们的键和值。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)