我想写来检查,如果一个字符串是一个字谜与否代码。但是,我不断收到错误的那个“你不能分配给一个恒定的变量”。我明白这意味着什么,但是对此的解决方案是什么?查找两个字符串是否字谜或者在C++中
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
bool check_str(const string& a, const string& b)
{
// cant be the same if the lenghts are not the same
if (a.length() != b.length())
return false;
//both the strings are sorted and then char by char compared
sort(a.begin(), a.end());
sort(b.begin(), b.end());
for (int i = 0; i < a.length(); i++)
{
if (a[i] != b[i]) //char by char comparison
return false;
}
return true;
}
int main()
{
string a = "apple";
string b = "ppple";
if (check_str(a, b))
{
cout << "Yes same stuff" << endl;
}
else
{
cout << "Not the same stuff" << endl;
}
system("pause");
}
a和b是常数。你不能对它们进行排序。 – drescherjm
随着你已经得到的答案,请注意,你不需要明确地比较char字符。只需'返回一个== b;'将单独比较字符。 –
该修改的重点是什么?另外,如前所述,你在函数结尾添加的'if ... else ...'可以简化为'return a == b;'。 –