Can I assign 2 variables at the same time in C ++?

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

Can I do something like this? And How?

+8
source share
4 answers

In C ++ 11, tuple and tie types can be used for this.

 #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); 
+17
source

You can do this in two ways:

  • Create a structure with two values ​​and return it:

     struct result { int first; int second; }; struct result DFS(a, b, c, d) { // code } 
  • Display parameters:

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

    call with:

     DFS(a, b, c, d, first, second); 
+3
source

If C ++ 11 is not possible, you can use links.

Passing a reference to the variables in the parameters.

 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); 
+1
source

One thing you should know is that if a, b, c, d are not base types, but the instances of the class you define, say Foo, and you overload the class operator =, you must ensure that the operator returns the link on the object that is assigned, or you cannot assign chains (solution = cost_limit = DFS (..) will only assign cost_limit). The = operator should look like this:

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

Source: https://habr.com/ru/post/905811/


All Articles