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

时间:2015-06-08 14:10:42

标签: c++

所以,我正在开发一个逻辑,用于在sort函数中使用自定义比较器将所有字符串分组在一起,只有当字符串都是字符串时才会返回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);
}

现在,这段代码没有编译并显示错误,即字符串无法在mycomp中传递。并显示了很多错误。另外,我的逻辑是否正确?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

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引用,则必须为排序创建副本。

相关问题