c++ - 有关简单C++函数的逻辑的问题(is_palindrome)

标签 c++ palindrome

下面的函数应该检查输入参数是否是回文,并返回true / false。

我知道代码中有一个错误,应该是:int i = text.size()-1 ;

问题:如果我不添加“-1”并打印出text和textR,它们都将是“女士”,据我理解,当我检查(text == textR)时,它应该是正确的。但是,它确实返回false

有人可以解释一下我在想什么吗?

我知道这与string.size()和字符串内容不是同一件事有关,并且字符串索引以0开头...我仍然不完全理解为什么text!= textR。

#include <iostream>
#include <bits/stdc++.h> 

// Define is_palindrome() here:

bool is_palindrome(std::string text) {

  // create an empty string to store a reversed version of text 
  std::string textR;

// iterating backward over text and adding each character to textR
  for (int i = text.size(); i >= 0; i--) {
    textR.push_back(text[i]);
  }

std::cout << text << std::endl;
std::cout << textR << std::endl;

  // check if the reversed text is the same as text; return true or false

  if (text == textR) {
    return true;
  } else {
    return false;
  }
}

int main() {

  std::cout << is_palindrome("madam") << "\n";

}

最佳答案

text[text.size()]'\0'(nul字符),无法打印。

因此TextR"\0madam"而不是预期的"madam"

关于c++ - 有关简单C++函数的逻辑的问题(is_palindrome),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60339643/

相关文章:

python - 检查字符串是否为回文,忽略空格和特殊字符

python - 递归函数不起作用

c++ - 如果模板类不尝试存储彼此的实例,它们可以相互依赖吗?

c++ - 从 Fortran 例程调用多线程 (openmp) c++ 例程

c++ - 如何创建 Gdk::Pixbuf 实例的 std::map 并在 Gdk::Cairo 中使用它

python - 在 Python 中测试回文

c++ - 已释放的堆未被回收?

c++ - 我需要一些建议来为我的模拟找到足够的算法

python - 欧拉问题 #4

C 可以推测我想用哪个数组来存储我的字符吗?