T
T
Tolik2014-05-05 18:02:31
C++ / C#
Tolik, 2014-05-05 18:02:31

What is the most convenient (compact) way in C++ to assign two variables by calling a function once?

In Python I have for example:

def func(a, b):
  return (a, b)

(x, y) = func(1, 2) # x = 1, y = 2

but in C++ it is much more difficult to do:
int *func(int a, int b) {
  int res[2];
  res[0] = a;
  res[1] = b;
  return res;
}

// способ 1 (но мне нельзя вызывать функцию 2 раза!)
x = func(1, 2)[0];
y = func(1, 2)[1];

// способ 2
int *a = func(1, 2);
x = a[0];
y = a[1];
// 3 строки писать для такой фигни?!

How can these three lines be made more compact? Delete \n doesn't count :D

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Popov, 2014-05-05
@Diel

First, your code is wrong.
The res array is local to the func function, and using a pointer to it after the function returns is undefined behavior. You're just lucky that the code works.
As for solutions - the closest thing to python code is to use std::tie (introduced in C++11):

std::pair<int, int> func()
{
    return std::make_pair(1, 2);
}

int x, y;
std::tie(x, y) = func();

Another, most common way is to pass references or pointers to variables in which the answer should be placed in the function parameters.
void func(int &res1, int & res2)
{
    res1 = 1;
    res2 = 2;
}

int x, y;
func(x, y);

L
lookid, 2014-05-05
@lookid

it is necessary to do much more difficult
Welcome to C++. What did you think? Rivet scripts and become the second Carmack?
https://github.com/vancegroup-mirrors/bullet-physi...
Here is the scalar product of vectors in ~1500 lines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question