c++ - Storing and accessing a pointer to an array in a std::map -


the scenario is: writing framework particle simulation application. need add various attributes particles, don't know yet , different per particle. since attribute accessed , manipulate quite in time critical manner, decided store them in plain c array. prefer access different kind of attributes (like pos, vel, force, etc.) name. decided use std::map<const std::string,double*> store floating point attributes.

so question. try store particle attribute values following

double* attr = new double[3 * 10]; std::map<std::string,double*> doubleattributes3d; doubleattributes3d.insert(std::make_pair("pos", attr));  for(int64_t = 0;i<10;++i) {     *(doubleattributes3d["pos"] + 3 * i) = 1.0;     *(doubleattributes3d["pos"] + 3 * + 1) = 2.0;     *(doubleattributes3d["pos"] + 3 * + 2) = 3.0; }  double * ptr = doubleattributes3d["pos"]; for(int64_t = 0;i<10;++i) {     cout << *(ptr + 3 * i) << " ";     cout << *(ptr + 3 * + 1) << " ";     cout << *(ptr + 3 * + 2) << endl; } 

which causes segfault. in particular, everytime when try access elements of array.

first question: there possibility can ever work? (i had never need of using map before, maybe produce error due syntax mistakes...) or in other words why can't access memory address stored map?

second question: there another/better(/actually working) way of storing unknown number of arrays , give them "name" in order access , manipulate them later?

i know there similar questions asked around here none of answers worked out me. lot

first question's awnser: tried run , run without issues, producing expected results. used valgrind on , reported no undefined behaviour. error must elsewhere or fixed when changed bounds of cycle.

second question's awnser: how many variables have there? std::map useful if there lot of variables , of them unset particles. in cases, it's more comfortable , far faster index properties enum, can used address standard c array. example:

enum pp {    pos,    vel,    force,    charge,    mass,    electron_configuration,    ppmax  }  double* particles[1000][ppmax];  particles[0][pos] = new new double[3 * 10];  // et cetera 

i benchmarked similar issue , difference in speed significant, if had set unused pointers nullptr. don't think additional spacial complexity matters in case.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -