How is this C++ function returning two values?

2.2k Views Asked by At

Please explain how this function is returning two values. It is taking an array and returning the two numbers from the array whose sum is equal to target sum.

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
    int a = 0;
    int b = 0;
    for (int i=0; i<nums.size()-1; i++)
    {
        for (int j=i+1; j<nums.size(); j++)
        {
            if (nums[i] + nums[j] == target)
            {
                a = i;
                b = j;
            }
        }
    }
    return {a, b};
    }
};
2

There are 2 best solutions below

0
On

The class std::vector has a constructor with the first parameter of a specialization of the template std::initializer_list<T> and that correspondingly accepts an initializer list.

vector(initializer_list<T>, const Allocator& = Allocator());

Such a constructor is called initializer-list constructor.

So when in the return statement there is used a braced list of objects of the same type, the compiler tries to use this braced list as an argument of the constructor that accepts an initializer list to build the returned object of the specified return type.

In fact, under the hood there is used the following action:

std::vector<int> temporary_object = { a, b };

So the function returns only one object (container) of the type std::vector<int> (the returned type of the function) that contains two elements of the type int.

3
On

The function returns a vector : vector<int> twoSum(...) { ... }. The line return {a, b}; calls the constructor of a vector, initialized with two values. This is equivalent to:

vector<int> myVector;
myVector.push_back(a);
myVector.push_back(b);
return myVector;