说我有
struct S { double A; double B; double C; };和
std::vector<S> vecS(10);我想写一个泛型函数void F(std::vector<S> vecS,structure Sx) ,以便下面的计算可以发生
F(std::vector<S> vecS, structure S.x) { for(i=1;i<10;i++) vecS[0].x += vecS[i].x; // note the structure does not have memeber "x" // I want to give that as a generic input to access A,B or C }上面的代码是不正确的代码,但我只是试图展示我想要计算的东西。
我想要计算的是循环遍历结构向量的特定元素。 这可能是一个简单的好方法吗? 有人可以给我一些指针,如何以通用的方式访问结构的成员(也许这是我需要写这个函数)。
提前致谢。
say I have
struct S { double A; double B; double C; };and
std::vector<S> vecS(10);I am trying to write a generic function void F(std::vector<S> vecS,structure S.x) such that the following computation can happen
F(std::vector<S> vecS, structure S.x) { for(i=1;i<10;i++) vecS[0].x += vecS[i].x; // note the structure does not have memeber "x" // I want to give that as a generic input to access A,B or C }The above code is not correct code, but I am just trying to demonstrate what I am trying to compute.
What I am trying to compute is loop over the vector of structs for a specific element. Is this possible in a simple nice way? Can someone please give me some pointers how to access a member of a structure in a generic way (maybe that is what I need to write this function).
Thanks in advance.
最满意答案
你需要的是一个指向成员的指针:
void F( std::vector<S> &vecS, double S::*ptr ) { for(i=1;i<10;i++) vecS[0].*ptr += vecS[i].*ptr; } // now call for A F( vec, &S::A );如果您需要使用不同类型的工具,则不仅可以使用这种模板,还可以使用模板。
PS我没先注意到,但你必须传递矢量作为参考,因为你修改了元素。
What you need is a pointer to member:
void F( std::vector<S> &vecS, double S::*ptr ) { for(i=1;i<10;i++) vecS[0].*ptr += vecS[i].*ptr; } // now call for A F( vec, &S::A );If you need it to work with different types, not only double as in this case, use template.
PS I did not notice first, but you have to pass vector as reference, as you modifying element in it.
更多推荐
发布评论