标准字符串查找方法和计数算法的逻辑错误

Logical error from std string find method and count algorithm

当我要用C++解决一个项目的欧拉问题时,这是我做的一些实验代码。它产生了一个意想不到的结果,所以我用其他编程语言解决了它。但是我真的很想明白为什么会出现这个错误。代码的第一部分按预期执行,它不打印 AAAA。但在第二部分中,逻辑上等效的代码(if 语句)在变量 s 为 AAAA 时执行。我不知道为什么。我希望我说清楚了我的问题,非常感谢给出的每个答案!谢谢:)

注意:我使用的是 <algorithm>

的计数
#include <iostream>
#include <algorithm>

using namespace std;

int main (int argc, char** argv) {
  string alt = "LOA";

  // CODE PART 1
  string stringToFind = "AAA";

  string df = "AAAA";

  if (df.find(stringToFind) == string::npos && count(df.begin(), df.end(), 'L') <= 1) {
    cout << df; // this does not print AAAA
  }

  /* CODE PART 2:
    this was an attempt to print out every four length string combination
    of the characters L, O, A where strings with three A's in a row and
    more than one L were excluded.
  */
  for (size_t i = 0; i < 3; i++) {
    char c1 = alt[i];
    for (size_t iT = 0; iT < 3; iT++) {
      char c2 = alt[iT];
      for (size_t itr = 0; itr < 3; itr++) {
        char c3 = alt[itr];
        for (size_t itrI = 0; itrI < 3; itrI++) {
          char c4 = alt[itrI];
          string s = string(&c1)+string(&c2)+string(&c3)+string(&c4);

          if (s.find(stringToFind) == string::npos && count(s.begin(), s.end(), 'L') <= 1) {
            cout << s << endl; // this however, does print out AAAA
          }
        }
      }
    }
  }
  return 0;
}

你写了

          string s = string(&c1)+string(&c2)+string(&c3)+string(&c4);

你的意思是:

          string s = string(1,c1)+string(1,c2)+string(1,c3)+string(1,c4);

          string s = string(&c1,1)+string(&c2,1)+string(&c3,1)+string(&c4,1);

在您的代码中,您调用了字符串构造函数,该构造函数采用指向以 nul 结尾的 char 数组的指针,但您为它提供了指向单个 char 的指针。这将调用各种未定义的行为。

要么调用采用计数器 + 单个字符的构造函数,要么调用采用指针和计数的构造函数,您可以告诉它在该地址处恰好有一个字符。

Edit 没有采用单个字符的构造函数。你必须给它一个计数+字符。这意味着它不是那么漂亮。