0

This is my code

#include <iostream>
using namespace std;
#include <vector>

// class to solve the 2sum problem
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector <int> ret;
        int size = nums.size();

        for (int i = 0; i < size - 1; i++)
        {
            for (int j = 0; j < size; j++)
            {
                if(nums[i] + nums[j] == target)
                {
                    ret.push_back(i);
                    ret.push_back(j);
                    return ret;
                }
            }
        }
        return ret;
    }

};


int main()
{
    // vector<int> A[] = {1,2,3,4};
    int l = 4;
    Solution s;

    s.twoSum({1,2,3,4},l); // calling the method
    return 0;
}

Am I doing something wrong? I am assuming that I am not calling the function into the main function correctly, hence the error. If I run the program without calling the function, it compiles and runs without error.

  • `{1,2,3,4}` is parsed as a temporary value, which in C++ cannot be bound to a mutable reference, only a `const` reference. Change `twoSum`'s parameter to a reference to a `const` object, and the shown code will compile. See the linked question, and the corresponding chapter in your C++ textbook, for more information. – Sam Varshavchik Sep 07 '22 at 01:03

0 Answers0