Home > Enterprise >  error: invalid operands to binary expression ('vector<int>' and 'int')
error: invalid operands to binary expression ('vector<int>' and 'int')

Time:09-17

Given an array of 2n elements, pair it in n elements and then find the sum of the minimum element in each pair and then maximize the sum. I wrote a class for this:

class Solution 
{
public:
    int sum = 0, n;

    int arrayPairSum(vector<int>& nums)
    {
        sort(nums, nums   2 * n);
        for (i = 0; i < 2 * n; i = i   2) 
        {
            sum = sum   nums[i];
        }
        return sum;
    }
};

but its showing me following error.

Line 5: Char 23: error: invalid operands to binary expression ('vector<int>' and 'int')
        sort(nums,nums 2*n);
                  ~~~~^~~~
/usr/bin/../lib/gcc/x86_6

How should I remove this error?

CodePudding user response:

The error is from this line

sort(nums, nums 2*n);
           ^^^^^^^^^

here you are trying to add 2*n to the vector of ints (i.e. nums). This is not defined, and hence the compiler error.

You need to pass the iterators to the std::sort.

#include <algorithm>

std::sort(nums.begin(), nums.end());

In addition, be aware in the condition of the for-loop that,

for(i=0; i<2*n; i=i 2) 
         ^^^^^

n must be initialized and 2*n must be less than or equal to nums.size() (i.e. size of the vector nums). Otherwise, your code will have undefined behavior.


Also, do not practice with using namespace std;. See here for more:

Why is "using namespace std;" considered bad practice?

CodePudding user response:

sort(nums, nums 2 * n) would works if nums was pointer or iterator;

here it would be sort(nums.begin(), nums.begin() 2 * n);

but nums.begin() 2 * n presupposes some relationship between nums and n which can probably be removed using nums.size() instead.

  • Related