C ++中的并行分配 [英] Parallel assignment in C++

查看:39
本文介绍了C ++中的并行分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中有什么方法可以进行并行赋值吗?目前,以下代码会编译(带有警告)

Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)

#include <iostream> 

int main() { 
  int a = 4;
  int b = 5;
  a, b = b, a;
  std::cout << "a: " << a << endl
            << "b: " << b << endl;

  return 0;
}

并打印:

a: 4
b: 5

我想要打印的内容...如果不明显,是:

What I'd like it to print ... if it weren't obvious, is:

a: 5
b: 4

例如ruby或python.

As in, say, ruby, or python.

推荐答案

这是不可能的.您的代码示例

That's not possible. Your code example

a, b = b, a;

的解释方式如下:

a, (b = b), a

它什么都不做.逗号运算符使其返回a(最右边的操作数)的值.因为赋值绑定更紧密,所以b = b在括号中.

It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens.

正确的方法只是

std::swap(a, b);

Boost包含一个元组类,您可以使用它

Boost includes a tuple class with which you can do

tie(a, b) = make_tuple(b, a);

它在内部创建一个对a和b的引用的元组,然后为它们分配一个b和a的元组.

It internally creates a tuple of references to a and b, and then assigned to them a tuple of b and a.

这篇关于C ++中的并行分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆