c++ - 如何初始化一个 div_t 对象?

标签 c++ division member modulo

所以从 div 返回的成员顺序函数似乎是实现定义的。

quot 是第 1 个 成员还是 rem

假设我正在做这样的事情:

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

当然这里的问题是我不知道我是否在我的 lambda 捕获中初始化了 i.quoti.rem。使用 div(quot, 1) 初始化 i 是唯一的跨平台方式吗?

最佳答案

你是对的,成员的顺序是未指定的。该定义是从 C 继承的,它明确指出它是(强调我的):

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. [...]

在 C 中,未指定顺序这一事实无关紧要,并且包含一个专门针对 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 };

不幸的是,C++ 从未采用这种语法。

我可能会在辅助函数中进行简单赋值:

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

对于普通的 int 值,无论您使用初始化还是赋值并不重要,它们具有相同的效果。

除以 1 也是一个有效选项。

关于c++ - 如何初始化一个 div_t 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41556257/

相关文章:

python - boost.python C++ 多线程

c++ - luabind:无法从非内置类索引的表中检索值

python - 负整数除法令人惊讶的结果

javascript - 如何让 Javascript 中的除法运算符起作用?它认为这是一个正则表达式

haskell - div 和 quot 之间的确切区别

c++ - 静态数据成员是否可以在 C++ 中键入其容器类型?

java - 递归地使 Java 中的成员对象无效?

c++ - 对 `_imp___ZN7QWidget14setWindowTitleE7QString' 的 undefined reference

c++ - C++ 中变量的别名如何工作

javascript - javascript 'function'/object 中的成员函数表示它不是一个函数