排序 std::vector<std::string *> 重载 <

Sort std::vector<std::string *> overloading <

#include <iostream>
#include <vector>
#include <algorithm>

bool operator<(std::string& str_1, std::string& str_2){
    std::cout<<str_1[0] <<" < " << str_2[0] << std::endl;
    return str_1[0] < str_2[0];
}
int main(int argc, const char * argv[]) {
    std::string str1 = "abc";
    std::string str2 = "def";
    std::string str3 = "ghi";
    std::string str4 = "bcd";
    std::string str5 = "fgh";

    //test the operator first
    std::cout << (str1<str2) << std::endl;

    std::vector<std::string *> str_vector;
    str_vector.push_back(&str1);
    str_vector.push_back(&str2);
    str_vector.push_back(&str3);
    str_vector.push_back(&str4);
    str_vector.push_back(&str5);

    std::sort(str_vector.begin(), str_vector.end());

    for (std::vector<std::string *>::iterator it=str_vector.begin(); it!=str_vector.end(); ++it)
        std::cout << ' ' << **it << std::endl;

    return 0;
}

该运算符似乎实现得很好,但在 std::sort() 期间从未调用过 这是控制台输出:

a < d
1
 fgh
 bcd
 ghi
 def
 abc
Program ended with exit code: 0

谢谢!

您为 string::string 重载了 operator<,但 str_vector 包含 std::string *

由于您无法更改指针等基本类型上运算符的行为,因此您需要提供一个自定义比较器作为 std::sort 的最后一个参数。例如 lambda:

std::sort(str_vector.begin(), str_vector.end(),
[](const std::string *str_1, const std::string *str_2){
    std::cout << (*str_1)[0] <<" < " << (*str_2)[0] << std::endl;
    return (*str_1)[0] < (*str_2)[0];
});

您有一个指向类型为 std::string

的对象的指针向量
std::vector<std::string *> str_vector;

因此,如果您在不指定比较函数的情况下调用标准算法 std::sort,则该算法将尝试对向量进行排序,比较指针本身而不比较指向的对象。

但是,如果您要声明 std::string 的对象向量而不是指针,那么您的重载 operator < 将不会被发现,因为函数 std::sort 的定义在命名空间中std 并且在这个命名空间中会发现标准重载 operator <.

如果您要使用自己的比较函数(例如 lambda 表达式),则可以使用自己的重载 operator < 对指针向量进行排序。

这是一个演示程序。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

bool operator <( const std::string &s1, const std::string &s2 )
{
    std::cout << "Bingo\n";

    return s1[0] < s2[0];
}

int main() 
{
    std::string s[] = { "abc", "def", "ghi", "bcd", "fgh" };

    std::vector<std::string *> v1;
    v1.reserve( sizeof( s ) / sizeof( *s ) );

    std::transform( std::begin( s ), std::end( s ), std::back_inserter( v1 ),
                    []( auto &s ) { return &s; } );

    std::sort( std::begin( v1 ), std::end( v1 ), 
               []( const auto &p1, const auto p2 )
               {
                    return *p1 < *p2;
               } );                 

    for ( const auto &p : v1 )
    {
        std::cout << *p << ' ';
    }
    std::cout << '\n';

    return 0;
}

程序输出为

Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
Bingo
abc bcd def fgh ghi 

如您所见,由于字符串 "Bingo" 的测试输出,您的 operator < 被调用。