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

标签 c++ stl std

当我准备用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 的指针。这将调用各种未定义的行为。

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

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

关于c++ - 标准字符串查找方法和计数算法的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34298025/

相关文章:

c++ - 存储未排序的键值对

c++ - 专门化命名空间中的模板——命名空间别名真的是别名吗?

c++:是否有类似 "boost/std typetraits conditional"的东西在编译时生成一个值(不是类型)?

c++ - 我可以将一个编译生成的目标文件链接到另一个编译生成的目标文件吗?

c++ - MFC 64 位代码在 Windows Server 2008 R2 上比 32 位慢

c++ - 是否有可能在任何地方引发异常的 STL 容器方法列表?

c++ - 创建 is_primitive 或 is_inheritable 模板

c++ - FreeRTOS CPP 函数指针

c++ - MPI发送和接收的通信成本

C++ std::map 和 std::pair<int, int> 作为键