Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set all struct members to same value?

Tags:

c++

I have a struct:

struct something {
    int a, b, c, d;
};

Is there some easy way to set all those a,b,c,d into some value without needing to type them separately:

something var = {-1,-1,-1,-1};

Theres still too much repetition (lets imagine the struct has 30 members...)

I've heard of "constructs" or something, but i want to set those values into something else in different part of the code.

like image 897
Newbie Avatar asked Jul 03 '10 22:07

Newbie


1 Answers

This is my second answer for this question. The first did as you asked, but as the other commentors pointed out, it's not the proper way to do things and can get you into trouble down the line if you're not careful. Instead, here's how to write some useful constructors for your struct:

struct something {
    int a, b, c, d;

    // This constructor does no initialization.
    something() { }

    // This constructor initializes the four variables individually.
    something(int a, int b, int c, int d) 
        : a(a), b(b), c(c), d(d) { }

    // This constructor initializes all four variables to the same value
    something(int i) : a(i), b(i), c(i), d(i) { }

//  // More concise, but more haphazard way of setting all fields to i.
//  something(int i) {
//      // This assumes that a-d are all of the same type and all in order
//      std::fill(&a, &d+1, i);
//  }

};

// uninitialized struct
something var1;

// individually set the values
something var2(1, 2, 3, 4);

// set all values to -1
something var3(-1);
like image 123
Gunslinger47 Avatar answered Sep 24 '22 19:09

Gunslinger47