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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With