0

I have a class that needs to be able to look up values in a global stl map object. However, I don't want each class to have a copy since the global object is pretty large. My current implementation is like this:

#include obj.h
#include init.h
map <string, vector<float> > gMap;
main() {int argc, char* argv[1]) {
  gMap = init(); // function in init.h that simply creates a map and returns it
  MyObj (); 
}

in obj.h, there is an extern to gMap.

I'm curious if there are better ways to accomplish what I want to here. Ideas?

I also plan to export this to Python via SWIG, and this presents a little problem in the current situation (this is some of the motivation for rethinking this). So if any solutions are simple enough to work with minimal problems in SWIG, that would be very good.

Thanks!

4

2 回答 2

3

最好的选择可能是将巨型地图存储在 std::shared_ptr(或 boost::shared_ptr)中,然后将其作为参数或成员传递给任何需要它的东西。

#include obj.h
#include init.h
#include <memory>
main() {int argc, char* argv[1]) {
  std::shared_ptr<map <string, vector<float> >> gMap; = init(); // function in init.h that simply creates a map and returns it
  MyObj f(gMap); 
}

另一种解决方案是通过引用任何需要它的东西来传递它。然而,成员引用可能很烦人。

于 2012-05-25T00:24:44.323 回答
0

In C++11 you can use initializer lists to achieve this. If the init function uses some constant values to initialize the map, then instead of creating it in the init function, you can just use this feature:

#include <map>
#include <string>
#include <vector>

std::map<std::string, std::vector<float>> gMap = {  
    {"foo", {1.5, 1.2, 6.4}},
    {"bar", {1.5, 1.2, 6.1}}
};

int main() {
    use_gmap(gMap);
}
于 2012-05-25T01:38:06.410 回答