【问题标题】:Can i assign in 2 variables at the same time in C++?我可以在 C++ 中同时分配 2 个变量吗?
【发布时间】:2012-02-08 15:39:19
【问题描述】:
int DFS(a, b,c,d)
{
    first=a+b;
    second=c+d;
    return(first,second);
}

solution, cost_limit = DFS(a, b,c,d);

我可以这样做吗?如何?

【问题讨论】:

  • 很不清楚你在这里问什么。我建议您解释一下分配的含义以及变量的含义。

标签: c++


【解决方案1】:

您可以通过两种方式做到这一点:

  1. 创建一个具有两个值的结构并返回它:

    struct result
    {
        int first;
        int second;
    };
    
    struct result DFS(a, b, c, d)
    {            
        // code
    }
    
  2. 输出参数:

    void DFS(a, b, c, d, int& first, int& second)
    {
        // assigning first and second will be visible outside
    }
    

    致电:

    DFS(a, b, c, d, first, second);
    

【讨论】:

  • 这显然不是 OP 所要求的。他要求将两个单独的值返回到两个单独的变量中。
  • 这不是他要求的。他想要pythonic方式,意思是solution = first; cost_limit = second;
【解决方案2】:

在 C++11 中,您可以使用元组类型和 tie

#include <tuple>

std::tuple<int, int> DFS (int a, int b, int c, int d)
{
    return std::make_tuple(a + b, c + d);
}

...

int solution, cost_limit;
std::tie(solution, cost_limit) = DFS(a, b, c, d);

【讨论】:

  • 如果 C++11 不是一个选项,Boost Tuple library 提供这些功能。
  • 如果 C++11 不是一个选项,你仍然可以使用 C++03 的std::pair&lt;int, int&gt;
  • @Antionio:但是 C++03 中没有 tie,所以它看起来很丑:std::pair&lt;int, int&gt; result = DFS(a,b,c,d); solution = result.first; cost_limit = result.second;
  • 您可以使用 TR1,我认为它还具有元组库(使用 tie
  • 在 C++17 中,使用带对的结构化声明
【解决方案3】:

您应该知道的一件事是,如果 a,b,c,d 不是基类型,而是您定义的类的实例,比如 Foo,并且您重载了该类的 = 运算符,则必须确保事实上,运算符将返回对已分配对象的引用,否则您将无法链接分配(solution = cost_limit = DFS(..) 只会分配给 cost_limit)。 = 运算符应如下所示:

Foo& Foo::operator =(const Foo& other)
    {
       //do stuff
       return other;
    }

【讨论】:

    【解决方案4】:

    如果不能使用 C++11,则可以使用引用。

    通过在参数中传递对变量的引用。

    int DFS(int a, int b, int c, int d, int &cost_limit)
    {
        cost_limit = c + d;
        return a + b;
    }
    
    int solution, cost_limit;
    
    solution = DFS(a, b, c, d, cost_limit);
    

    【讨论】:

      【解决方案5】:

      使用 C++17,您可以解包一对或元组

      auto[i, j] = pair<int, int>{1, 2};
      cout << i << j << endl; //prints 12
      auto[l, m, n] = tuple<int, int, int>{1, 2, 3};
      cout << l << m << n << endl; //prints 123
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-16
      • 2016-09-04
      • 2015-11-09
      • 2019-08-31
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      相关资源
      最近更新 更多