c++11 - How to pass fields from a class to function in c++? -
in words: how can pass various fields custom class single function?
now in details: have std::vector
containing class, example customclass
have extract result field class criteria fields in class , combine somehow data.
my first approach problem use function accepts parameter std::vector
of class in order extract data , return std:map
. key in map type of criteria data should combined , value int
combined data members of vector.
the problem criteria not 1 - more 1 field class may used criteria (let easiness of criteria std::string
, if not - make function templated).
the easiest way me make dozens of functions identical code , each of them extract simple concrete field class. changes might require similar changes of dozens of functions maintenance headache. in stage cannot think how pass single function field class...
here's example code class:
// class data , criteria class customclass { public: std::string criteria1; std::string criteria2; std::string criteria3; //... , others criteria int datatobecombined; // other code }; // 1 of these functions std::map<std::string, int> getdatabycriteria1(std::vector<customclass> avector) { std::map<std::string, int> result; foreach(customclass anobject in avector) { if(result.find(anobject.criteria1)==result.end()) // if such of key doesn't exists { result.insert(std::make_pair(anobject.criteria1, anobject.datatobecombined)); } else { // other stuff in order combine data } } return result; }
and similar way should make other functions should work customclass::criteria2
, customclass::criteria3
, etc.
i thought make these criteria in single array , pass function number of criteria class used others other purposes , fields must easy read, not option (i.e. real names not criteria1
, criteria2
, etc. descriptive).
anyone ideas?
edit: referred question "c++ same function parameters different return type" different - function in case return same type every time, parameters takes must various fields class.
you can use function extract filed such as
std::string extractfiled(const customclass &object, int which) { switch (which) { case 1: return object.criteria1; case 2: return object.criteria2; case 3: return object.criteria3; default: return object.criteria1; } }
and getdatabycriteria
add arg indicate filed use. or can use macro implement getdatabycriteria
.
Comments
Post a Comment