std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值
std::string::find returns different value for dereferenced iterator and equivalent string literal
这是我的代码块:
for (auto it = name.begin(); it != name.end(); it++) {
cout << "n" << "Fetching " << *it;
cout << int(buf.find("cse3")) << "n";
cout << int(buf.find(*it)) << "n";
if (buf.find(*it) == string::npos) {
cout << "No description for " << *it;
cout << "In " << buf;
} else if ...
...
}
哪里
vector<string> name = ...;
string buf = ...;
这是我得到的输出
Fetching cse3
0
-1
No description for cse3
In cse3" name="cse3"
我试图查找类型,*it
给出了一个只是字符串的basic_string<char>
,cse3
是一个A5_c
,根据我的研究,这意味着 5const array
。但是,为什么buf.find()
能够找到字符数组而找不到字符串?
此外,我还发现*it == cse3
实际上返回 0。我认为字符串的重载== operator
能够比较字符串和字符串文字。
为什么使用迭代器并取消引用它会得到一个奇怪的行为字符串?
如您所见,Fetching cse3
之后有一个换行符,这在您的代码中没有。这意味着向量中的字符串实际上是cse3n
的,所以没有找到它。
basic_string::find
没有错,这里有一个演示:
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> vec = { "abc", "abcn" };
string s = "abcdef";
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << static_cast<int>(s.find(*it)) << endl;
}
}
输出:
0
-1
相关文章:
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 在编译时检查字符串文本的长度
- 读取字符串文本输入以创建 2D 矢量
- 管理字符串文本的最佳做法
- 定义宏以将前缀 0x 添加到十六进制字符串文本
- 无法在模板参数中定义字符串文本
- 不推荐使用 PTCHAR 的字符串文本
- C++ 字符串文本和常量
- C++20字符串文本模板参数工作示例
- 返回从字符串文本创建的静态string_view是否安全?
- 在处理任何字符大小的模板中使用字符串文本
- 是否保证相同内容字符串文本的存储相同?
- 将以 null 结尾的字节字符串转换为原始字符串文本
- 是否可以创建一个用户定义的文本,将字符串文本转换为 own 类型的数组?
- 使用C++中的模板检测不同的字符串文本
- 无法完全专用化字符串文本的模板
- C++ - 确定 const char* 是指向字符串文本对象还是动态对象
- 是否可以在原始字符串文本中插入转义序列?
- C++带有捕获组的正则表达式字符串文本
- 为什么多维数组中的空字符串文本衰减为空指针?