如何使用自定义比较器函数将所有字谜组合在一起
How to group all anagrams together using a custom comparator function?
因此,我正在开发一种逻辑,用于在排序函数中使用自定义比较器将所有字谜分组在一起,只有当字符串都是字谜时才返回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引用,则必须为排序创建一个副本。
相关文章:
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- C++ std:: 并包括它们如何组合在一起?
- 通过字符串迭代并将每个循环中的先前字符组合在一起
- 如何将一个 while 循环与 for 循环组合在一起?
- 将两个数组组合在一起,形成每个项目的一对
- OpenGL 将来自 ttf 的渲染器文本与背景纹理组合在一起时出错
- 将PCH,PDB和Zi组合在一起会导致VS2017的C2859编译错误令人费解
- 在 switch 语句中将多个案例组合在一起
- 将两个矩阵组合在一起,然后用一个值组织另一个值
- 如何将array.h,array.cpp和main.cpp文件组合在一起
- Windows C - 需要想法 - 在同一应用/窗口中将鼠标输入和原始输入组合在一起
- 在 c++ 中将向量与一个或多个相似元素组合在一起
- 如何渲染成不同的层,然后将它们与OpenGL组合在一起
- 这就是我把两个小堆组合在一起的方式
- 试图将字符串的两个元素组合在一起会得到错误的结果(c++)
- 将两种方法组合在一起
- 我可以将一个可执行文件与另一个可执行文件(Windows 服务程序)组合在一起,并将该程序作为逻辑服务运行吗?
- 将两个常量char*组合在一起
- 读入两个文本文件,然后将它们组合在一起