C ++循环通过结构向量(C++ looping through a vector of structure)

编程入门 行业动态 更新时间:2024-10-24 20:13:33
C ++循环通过结构向量(C++ looping through a vector of structure)

说我有

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.

更多推荐

本文发布于:2023-07-28 23:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1310150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   结构   looping   vector   structure

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!