Today when I was doing leetcode 406, I met with a problem about operator overload. Specifically, I want to move the iterator to a certain position. I want to use operator = to achieve that. But when I finish the overload operator code, compiler shows an error:
overloaded 'operator =' must be a binary operator (has 3 parameters)
std::list<vector<int>>::iterator operator = (list<vector<int>>& it, int a) {
I don't know the meaning of that. Here is the code:
struct myclass {
bool operator() (vector<int>& a, vector<int>& b) {
if(a[0] == b[0]) return a[1] < b[1]; // if the height is same, the one with smaller k is prior!
return (a[0] > b[0]);
}
} compare;
class Solution {
public:
std::list<vector<int>>::iterator operator = (list<vector<int>>& it, int a) {
while(a-- > 0) {
it ;
}
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(), people.end(), compare);
list<vector<int>> que;
for(int i = 0; i < people.size(); i ) {
int pos = people[i][1];
std::list<vector<int>>::iterator it = que.begin();
it = pos;
que.insert(it, people[i]);
}
return vector<vector<int>>(que.begin(), que.end());
}
};
CodePudding user response:
You were probably trying to "fix" the compiler error in the line
it = pos;
operator =
has to have a specific syntax according to the standard.
If implemented as non-static member function, it will always have a hidden (except for C 23 deduced this) first parameter pointing to the class instantiation (*this
of type Solution
in your case).
The issue is caused by the container type you chose: std::list
has a (legacy) bidirectional iterator. That means you can only increase (e.g. it
) or decrease (e.g. --it
) it. If you'd would have used e.g. std::vector
, there would be a (legacy) random access iterator, and operator =
would already be defined.
It's often not a good idea to implement arithmetic operators for standard library types: they were not implemented in the first place for a reason.
Like mch said in the comments, the standard library has a function to increase the iterator a specific number of times: std::advance
. I.e., the line can be replaced with
std::advance(it,pos);
CodePudding user response:
When you do operator overloading as a non-static member function of a class, it is assumed that the first operand is the object through with the function is being called(non-static member functions are always called through an object), in other words, *this
.
So to avoid that, in your case(because you don't have access to the definition of the class list::iterator
), define the operator =
in a static context(outside the Solution class).
Another way would be to create a subclass to inherit the std::iterator
and then make some adjustments to the code. There you can directly overload the operator =
. But that would just be overkill.
Also why are you passing a list as the first argument? Shouldn't it be an iterator? I am assuming that is a typo.