The recursion problem with operator overloading

I have it:

typedef string domanin_name;

And then I try to overload the <operator like this:

bool operator<(const domain_name & left, const domain_name & right){
    int pos_label_left = left.find_last_of('.');   
    int pos_label_right = right.find_last_of('.');

    string label_left = left.substr(pos_label_left);
    string label_right = right.substr(pos_label_right);
    int last_pos_label_left=0, last_pos_label_right=0;

    while(pos_label_left!=string::npos && pos_label_right!=string::npos){
        if(label_left<label_right) return true;
        else if(label_left>label_right) return false;

        else{
            last_pos_label_left = pos_label_left;
            last_pos_label_right = pos_label_right;

            pos_label_left = left.find_last_of('.', last_pos_label_left);
            pos_label_right = right.find_last_of('.', last_pos_label_left);

            label_left = left.substr(pos_label_left, last_pos_label_left);
            label_right = right.substr(pos_label_right, last_pos_label_right);
        }
    }
}

I know this is a weird way to overload the <operator, but I have to do it this way. He must do what I want. It is not important.

The problem is that it introduces an infinite loop on this line:

if(label_left<label_right) return true;

He seems to be trying to use this overload function for comparison, but label_left is a string, not a domain name!

Any suggestion?

+3
source share
3 answers

typedef . , . , < , , , .

:

bool domain_less(domain_name const& left, domain_name const& right);

, , std::sort. < , . , std::ptr_fun, . -; , std::binary_function . ( <functional>.)

+1

typedef . . , operator < string.

,

struct domain_name {
   string data;
   // ...
};

.

+12

Typedef . Typedef - . . . .

+3

Source: https://habr.com/ru/post/1744038/


All Articles