std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值

std::string::find returns different value for dereferenced iterator and equivalent string literal

本文关键字:字符串 文本 返回 迭代器 find string 取消 std 引用      更新时间:2023-10-16

这是我的代码块:

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