user1612986
user1612986

Reputation: 1415

C++ looping through a vector of structure

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.

Upvotes: 3

Views: 100

Answers (3)

b4hand
b4hand

Reputation: 9770

The concept you are looking for is called a pointer to member. You can't use the exact syntax as you have written, and pointer to member syntax is rather ugly and not commonly used. But here's the basics.

double S::*x = &S::A;
vecS[0]->*x += vecS[i]->*x

See the following for more details:

Also, unrelated to your question, but you need to declare the type of your loop variable i. Currently, it is undefined.

Upvotes: 0

Slava
Slava

Reputation: 44268

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.

Upvotes: 5

MSalters
MSalters

Reputation: 179981

Well, it's not generic in the sense that you have a vector hardcoded, but let's ignore that for a second.

What you want is a pointer-to-member:

template <typename T, typename M>
F(std::vector<S> vecS, M T::* member) {
        for(i=1;i<10;i++)
          vecS[0].*member += vecS[i].*member;  
}

Call as F(vec, &myClass::A)

Upvotes: 1

Related Questions