简体   繁体   English

带有数组的C ++异构映射

[英]c++ heterogeneous map with arrays

I have seen people suggest using boost::any to have a heterogeneous map. 我见过有人建议使用boost :: any来拥有异构地图。 Ie

map<string,boost::any> 

Has anyone had any luck storing (and successfully using ) arrays stored in the map doing said technique? 有没有人做过上述技术来存储(成功地使用)存储在地图中的数组?

I have been able to do the following: 我已经能够做到以下几点:

boost::array<char,100> myArr;
map<string,boost::any> myMap;
myArr[51] = a; 
myMap["imageData"] = myArr;

The problem with this is that this seems to store the entire array in memory twice. 问题在于,这似乎将整个数组两次存储在内存中。 If I change it up a bit and do this: 如果我将其更改一下并执行以下操作:

boost::array<char,100> myArr;
map<string,boost::any> myMap;
myArr[51] = a; 
myMap["imageData"] = &myArr;

I have no idea how to get the data back out of the map. 我不知道如何从地图中获取数据。 How can I create a boost::array<char,100> pointer? 如何创建boost::array<char,100>指针? Can I? 我可以吗? Has anyone else been able to do something similar or has any ideas to do something similar in a more elegant way? 是否有其他人能够以更优雅的方式做类似的事情或有任何想法去做类似的事情?

Originally, I wanted to store a char[100] into the map but I could find no way to cast it once in the map (In order to use the data in the map, one must cast it to the proper type). 最初,我想将char[100]存储到地图中,但是我找不到将其在地图中强制转换一次的方法(为了使用地图中的数据,必须将其强制转换为正确的类型)。 A solution that would allow me to get a char[someSize] out of the map would be ideal. 一个允许我从地图中获取char[someSize]的解决方案将是理想的。

If you were not using boost::any, for instance doing something like: 如果您没有使用boost :: any,例如执行以下操作:

map<string, vector> myMap;
myMap["imageData"] = vector(100);

the compiler (GCC 4.6 in my case) would automatically avoid the extra copy. 编译器(在我的情况下为GCC 4.6)将自动避免多余的副本。 For some reason, boost::any is preventing that. 由于某种原因,boost :: any可以阻止这种情况。 One possible solution would be to use a shared_ptr : 一种可能的解决方案是使用shared_ptr

typedef boost::array<char, 100> Image;
map<string, boost::any> myMap;
myMap["imageData"] = boost::shared_ptr<Image>(new Image());

Using a shared_ptr in a container tends to be a much better solution that using a real pointer as you were suggesting in your question. 与在问题中所建议的使用实指针相比,在容器中使用shared_ptr往往是更好的解决方案。 The image would then be destroyed when there were no variable pointing at it, thus saving the programmer from manually freeing its memory. 当没有变量指向该映像时,该映像将被销毁,从而避免了程序员手动释放其内存。

Depending on the size of your images, however, the overhead of having two copies until the local variable goes out of scope may not be that high. 但是,根据图像的大小,在局部变量超出范围之前拥有两个副本的开销可能不会那么高。 So you should also consider the possibility of keeping your current solution. 因此,您还应该考虑保留当前解决方案的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM