如何使用自定义比较器函数将所有字谜组合在一起

How to group all anagrams together using a custom comparator function?

本文关键字:组合 在一起 何使用 自定义 比较器 函数      更新时间:2023-10-16

因此,我正在开发一种逻辑,用于在排序函数中使用自定义比较器将所有字谜分组在一起,只有当字符串都是字谜时才返回true,如果字符串的排序版本是等效的,则可以轻松检查。我开发了以下代码:

#include <iostream>
#include <string>
#include <algorithm>
bool mycomp (const string &a1, const string &a2);
#define N 5
using namespace std;
int main (void)
{
    int i;
    string arr[50];
    for ( i = 0; i < N; i++ )
    {
        cin>>arr[i];
    }
    sort(arr,arr+N,mycomp);
    for ( i = 0; i < N; i++ )
    {
        cout<<arr[i]<<"n";
    }
    return 0;
}
bool mycomp (const string &a1, const string &a2)
{
    string f1 = sort(a1.begin(),a1.end());
    string f2 = sort(a2.begin(),a2.end());
    return (f1 == f2);
}

现在,这段代码无法编译,并显示了一个错误,即string不能在mycomp中传递。显示了很多错误。还有,我的逻辑正确吗?谢谢你的帮助。

my_comp应为:

bool mycomp (std::string a1, std::string a2)
{
    std::sort(a1.begin(), a1.end());
    std::sort(a2.begin(), a2.end());
    return a1 < a2;
}

std::sort修改字符串时,如果传递const引用,则必须为排序创建一个副本。