'No viable Overloaded. "=" C++
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
int k=0;
int m=nums1.size();
int n=nums2.size();
vector<int> res[m];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(nums1[i]==nums2[j]){
res[k]=nums1[i];
k++;
break;
}
}
}
return res;
}
};
I had to find duplicates in two different arrays and return the same. But I'm getting the error
no viable overloaded '='
from the compiler in the line where I am storing my duplicates in the res[k] vector.
Solution 1:[1]
In this line you try to allocate an array of std::vectors.
vector<int> res[m];
But m is not constant so it causes a compilation error (C++ does not support VLA - see Why aren't variable-length arrays part of the C++ standard?).
I am not sure what exactly you are trying to do, but I believe you should change it to:
vector<int> res;
Then use push_back to add elements to it:
res.push_back(nums1[i]); // Instead of: res[k]=nums1[i];
You don't need to track the number of elements in the vector with k and you can eliminate it altogether.
2 more notes:
- The method
intersectcan be a static method (or a free functions) as it doesn't need access to any class members. - Your algorithm implementation compares each element in
nums1to each element innums2so you will get duplicates in the output array (not sure what was intended).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
