Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

c++ - How can I Initialize a div_t Object?

So the order of the members returned from the div functions seems to be implementation defined.

Is quot the 1st member or is rem?

Let's say that I'm doing something like this:

generate(begin(digits), end(digits), [i = div_t{ quot, 0 }]() mutable {
    i = div(i.quot, 10);
    return i.rem;
})

Of course the problem here is that I don't know if I initialized i.quot or i.rem in my lambda capture. Is intializing i with div(quot, 1) the only cross platform way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're right that the order of the members is unspecified. The definition is inherited from C, which explicitly states it is (emphasis mine):

7.20.6.2 The div, ldiv, and lldiv functions

3 [...] The structures shall contain (in either order) the members quot (the quotient) and rem (the remainder), each of which has the same type as the arguments numer and denom. [...]

In C, the fact that the order is unspecified doesn't matter, and an example is included specifically regarding div_t:

6.7.8 Initialization

34 EXAMPLE 10 Structure members can be initialized to nonzero values without depending on their order:

div_t answer = { .quot = 2, .rem = -1 };

Unfortunately, C++ never adopted this syntax.

I'd probably go for simple assignment in a helper function:

div_t make_div_t(int quot, int rem) {
  div_t result;
  result.quot = quot;
  result.rem = rem;
  return result;
}

For plain int values, whether you use initialisation or assignment doesn't really matter, they have the same effect.

Your division by 1 is a valid option as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...