Redefine <operator for use in stl algorithms for strings

Is it possible to redefine operator <std for strings without changing the namespace to use this operator in standard algorithms? For example, I can write:

namespace std
{

    bool operator <(const std::string & rhs, const std::string & lhs)
    {
        std::cout << "lol";
        return false;
    }

}

int main()
{
    std::vector<std::string> lol = { "a", "b", "ba", "aa" };
    std::sort(lol.begin(), lol.end());
}

and "lol" will be printed several times. But if I move operator <outside from the std namespace, the default value will be used operator <and nothing will be printed. Is it possible to do std::sortusing custom operator <without including it in the std namespace?

Yes, I know, I can pass another comparator to std :: sort, but I wonder if I can do what I asked and how?

Also I will correct that it is correct to add such specialization of the template to the std namespace?

: , , , .

+4
2

, . - undefined. [namespace.std]/1 :

++ undefined, std std, . std , , .

std::sort, lambda ,

std::sort(std::begin(foo), std::end(foo), [](const auto& lhs, const auto& rhs) { /* your code here */ });
+7

< std

, . , , , .

std:: sort < std?

, , :

, , std:: sort

.

, std?

; , std, undefined. , .

+6

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


All Articles