如何从函数返回两个值?

新手上路,请多包涵

如何设计一个函数原型,允许单个函数同时查找并返回数组中的最小值和最大值?谢谢你。

原文由 Bill Hicks 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 731
1 个回答

std::pair 涵盖返回两个值, std::tuple 推广到任意数量的值。并且通过 std::tuplestd::tie 实用函数,调用者也可以将结果接收到单独的变量中,避免需要一一提取它们,例如:

 std::tuple<int, int> returns_two()
{
  return std::make_tuple(1, -1);
}

int main() {
  int a, b;

  std::tie(a, b) = returns_two();

  // a and b are now 1 and -1, no need to work with std::tuple accessors
  std::cout << "A" << a << std::endl;
}

当然,在这种情况下,您实际上不需要滚动自己的代码来返回输入的最小值和最大值,因为已经有一个模板化的实用函数 std::minmax (对于两个离散的args and initializer lists) and std::minmax_element (for ranges defined by iterators) (which both return std::pair , and std::pair is fully compatible with std::tuple 两个元素)。

原文由 ShadowRanger 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏