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};
}
};
The class
std::vector
has a constructor with the first parameter of a specialization of the templatestd::initializer_list<T>
and that correspondingly accepts an initializer list.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:
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 typeint
.