从文本文件加载std :: map [英] load std::map from text file

查看:129
本文介绍了从文本文件加载std :: map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的事情,所以我想保持它的声音很简单。所有我想要的是从文件中加载一堆键值的paires,并将它们填充到地图中。我不太在乎文本的结构,只要它很容易阅读。



我现在是:




  • xs xsd生成代码(overkill)

  • 协议缓冲区(也是overkill)

  • INI样式文本文件



我喜欢INI文件的语法,但我不想为此写一个解析器。对我来说听起来好像我会做很多人在我之前做的事情。有没有一些图书馆可以读取像这样的简单结构化文件?

解决方案

既然你似乎想要最简单的事情, ,我会建议一些令人难以置信的简单,可能或可能不工作,基于你的地图内容。如果您的地图数据值是包含空格的字符串,这将不起作用。如果他们是没有空格或数字的字符串,那么你就被设置了。



这是没有测试的代码,但它是接近和简单的,所以你应该是罚款,即使它不完全编译。只需将KeyType和ValueType更改为int,string,float或您在文件中实际使用的任何内容。



设置文件如下:

 键值
key2 value2
key3 value3
key4 value4
pre>

阅读如下:

  KeyType键; 
ValueType值;

std :: map< KeyType,ValueType> MYMAP;
while(infile>>>>>> value)
myMap [key] = value;


This is a very simple thing, so I want to keep it as simple as it sounds. All I want is to load a bunch of key-value paires from a file, and populate them in to a map. I do not really care how the text is structured, as long as it is easy to read.

What i have now is:

  • xml with xsd generated code (overkill)
  • Protocol buffer (also overkill)
  • INI style text file

I like the syntax of the INI file, but I not want to write a parser for that. It sounds to me like I would be doing something lots of people have done before me. Is there not some sort of library to read simple structured files like this?

解决方案

Since you seem to want the simplest thing humanly possible, I'm going to suggest something incredibly simple that may or may not work based on your map contents. If your map data values are strings that include spaces, this wont work. If they're strings without spaces, or numeric, you're set.

This isn't tested code, but it's close and simple so you should be fine even if it doesn't quite compile. Just change KeyType and ValueType to int, string, float, or whatever you're actually using in the file.

Set up file like:

key value
key2 value2
key3 value3
key4 value4

Read like:

KeyType key;
ValueType value;

std::map<KeyType, ValueType> myMap;
while (infile >> key >> value)
    myMap[key] = value;

这篇关于从文本文件加载std :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆