我想寫來檢查,如果一個字符串是一個字謎與否代碼。但是,我不斷收到錯誤的那個「你不能分配給一個恆定的變量」。我明白這意味着什麼,但是對此的解決方案是什麼?查找兩個字符串是否字謎或者在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;'。 –