Hi I am trying to practice c and came across a error while solving a problem, I am using vectors in my code and getting error where I added two elements in vector through reference operator'[]'
C
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> temp;
int p = 0;
for (auto i = nums.begin(); i != (nums.end() - 1); i) {
cout<<*i;
p = nums[i] nums[i 1]; //Error is in this line
if ((p) == target) {
temp.push_back(i);
temp.push_back(i 1);
return temp;
}
}
}
};
Error: No viable overloaded operator[] for type vector
CodePudding user response:
i
is an iterator, not an index, so you don't need []
at all.
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
for (auto i = nums.begin(); i != (nums.end() - 1); i) {
std::cout<<*i;
if ((*i *(i 1)) == target) {
return { *i, *(i 1) };
}
}
throw std::runtime_error("no solution found");
}
};
However rather than writing the loop yourself, you could use the existing std::adjacent_find
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
auto i = std::adjacent_find(nums.begin(), nums.end(), [target](int a, int b) {
std::cout << a;
return (a b) == target;
});
if (i != nums.end()) {
return { *i, *(i 1) };
}
throw std::runtime_error("no solution found");
}
};
CodePudding user response:
I fixed your code, you cannot mix iterators with numeric values.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> temp;
int p = 0;
for (auto i = nums.begin(); i != (nums.end() - 1); i) {
cout << *i;
p = *i *(i 1); //now code works fine
if ((p) == target) {
temp.push_back(*i);
temp.push_back(*(i 1));
return temp;
}
}
}
};
when you use loop using iterators you shouldn't access into a vector via [] operator, because iterators are pointers to elements of the vector. simply use *i to access value iterator points to.