Thread: Iterating through Struct Members

  1. #1
    Registered User Vespasian's Avatar
    Join Date
    Aug 2011
    Posts
    181

    Iterating through Struct Members

    Suppose I have a struct with 20 members. I want to assign each of those structs with values. Instead of accesing by explicit convention, i.e.:

    Code:
    struct.member1 = 1;
    struct.member2 = 2;
    ...
    ...
    ...
    struct.member20 = 6;
    Is there any way to encapsulate it in a for loop and use an iterator variable to indicate the member? i.e.:

    Code:
    for (int i = 0; i < 20; i++)
    struct.i = i;
    The above is pseudocode but Im sure you get what Im trying to do?

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    that sort of thing requires reflection, which C++ currently does not have, although according to this blog post, it is being considered for the C++14 update.

    you could simply use an array if all of the members are the same type.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    A struct can contain an array.
    Code:
    struct X {int member[20];};
    
    int main()
    {
         struct X x;
         int i;
         for (i = 0; i < 20; ++i)
             x.member[i] = i;
    }
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to access members of a struct
    By Bnchs in forum C Programming
    Replies: 9
    Last Post: 03-25-2008, 02:28 PM
  2. accesing struct members
    By kennny2004 in forum C++ Programming
    Replies: 2
    Last Post: 05-23-2006, 11:31 PM
  3. What members does struct udphdr(linux) have?
    By failure_to in forum C Programming
    Replies: 2
    Last Post: 05-27-2004, 01:07 PM
  4. Pointer to struct members
    By kybert in forum C Programming
    Replies: 7
    Last Post: 07-01-2003, 08:27 AM
  5. comparing struct members
    By breed in forum C Programming
    Replies: 4
    Last Post: 11-22-2001, 12:27 PM