【问题标题】:Issue when using std::find with an array of std::string将 std::find 与 std::string 数组一起使用时出现问题
【发布时间】:2020-10-08 11:46:12
【问题描述】:

我正在尝试运行这个比较器:

if (std::find(movements->begin(), movements->end(), commandBuffer) != movements->end())

与:

const std::string movements[8] = {"north", "south", "east", "west", "n", "s", "e", "w"};

其中commandBufferstd::string

在 MinGW32 9.2.0 上,我得到以下信息:

错误:'operator==' 不匹配(操作数类型为 'const char' 和 'const std::__cxx11::basic_string')

【问题讨论】:

    标签: c++


    【解决方案1】:

    要么使用std::cbeginstd::cend,要么将您的数组更改为std::array

    std::array<const std::string, 8> movements = {"north", "south", "east", "west", "n", "s", "e", "w"};
    const std::string commandBuffer = "north";
    
    if (std::find(movements.begin(), movements.end(), commandBuffer) != movements.end())
        std::cout << "Found!" << std::endl;
    

    【讨论】:

      【解决方案2】:

      movements 是一个指向字符串数组的指针,基本上:

      const std::string* movements;
      

      movements-&gt;begin() 等于(movements[0]).begin() 并指向第一个字符串的第一个字符,而不是字符串本身。所以你正在迭代第一个字符串的字符。

      改为遍历字符串数组 使用begin(movemens), end(movements)

      如果您使用过std::vector&lt;string&gt; movementsstd::array&lt;string, N&gt;,您的代码也可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        • 2015-09-15
        • 2010-09-22
        • 1970-01-01
        • 2018-03-22
        • 2012-04-23
        相关资源
        最近更新 更多