-1 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");
}
Run Code Online (Sandbox Code Playgroud)
您尝试std::sort输入字符串可以修改它们,但您也声明了它们const(通过传递它们const std::string&),禁止修改它们.
通过价值,即
bool check_str(string a, string b)
Run Code Online (Sandbox Code Playgroud)
或非const引用,即
bool check_str(string& a, string& b)
Run Code Online (Sandbox Code Playgroud)
代替.后者将修改您的原始字符串,前者不会.此外,第一个变体将接受临时变体,而第二变体将不接受临时变体.
在我看来,通过值传递将是这里的方式,因为一些称为check_str修改其输入的函数似乎是反直觉的.
最后一点:正如评论中已经提到的,你不需要使用循环来比较字符串,你可以简单地将它们与之比较a == b.
| 归档时间: |
|
| 查看次数: |
245 次 |
| 最近记录: |