-1; 被计算之前将 -1 转-6ren">
gpt4 book ai didi

c++ - c++ 中的 find_first_of 给出不同的值

转载 作者:太空狗 更新时间:2023-10-29 19:48:04 26 4
gpt4 key购买 nike

在下面的代码中,我不明白为什么 b 是假的。

string s = "--p--";
cout << s.find_first_of("p") << endl; //prints 2
bool b = s.find_first_of("p")>-1;
cout << b << endl; //prints 0 (why?)

最佳答案

s.find_first_of("p") 返回一个 size_t,它是一个 unsigned 类型。

> 运算符会在 s.find_first_of("p")>-1; 被计算之前将 -1 转换为无符号类型.这就是 C++ 的工作原理:如果采用两个参数的运算符遇到一个 signed 和一个 unsigned 类型作为这些参数,那么 signed 将被转换到 unsigned 一个。

-1 转换为无符号类型时将是一个大的正数。 (事实上​​,它会环绕size_t的最大值。)

因此您的比较结果为 false

要检查字符是否不在字符串中,请使用 b = s.find_first_of("p") != string::npos;

关于c++ - c++ 中的 find_first_of 给出不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35274703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com