【发布时间】:2016-03-21 15:19:39
【问题描述】:
我正在尝试编写一个代码来检查一个字符串是否是一个字谜。但是我不断收到错误消息,即“您不能分配给恒定的变量”。我明白这意味着什么,但是解决方法/解决方案是什么?
#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 是常量。你不能对它们进行排序。
-
除了您已经得到的答案,请注意您不需要逐个字符显式比较。只需
return a == b;将单独比较字符。 -
编辑的意义何在?此外,如前所述,您刚刚在函数末尾添加的
if ... else...可以简化为return a == b;。 -
我删除了你令人困惑的编辑。
标签: c++