我正在学习使用 find
方法,据我所知,它返回一个迭代器到找到的项目,这是我的示例代码,我试图找到字符串“foo”
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> foo;
vector<string>::iterator v1;
vector<string>::iterator v2;
v1=foo.begin();
v2=foo.end();
foo.push_back("bar");
foo.push_back("foo");
std::vector<string>::const_iterator it = find(v1, v2, "foo");
cout<<*it;
}
当我尝试编译代码时出现以下错误
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)
我无法计算出对指针的尊重,看来我必须重载 <<
运算符,但奇怪的是我必须重载 <<
运算符来处理字符串,就像我已经可以做的那样
string boo = "bar"
cout<<boo;
这是怎么回事,我该如何解决这个问题??
最佳答案
我可以在 GCC 下编译它,但 MSVC 拒绝它。正如克里斯的评论所示,添加 #include <string>
解决问题。
然后您的程序在运行时崩溃了。您分配给了 v1
和 v2
在您将值分配给 vector 之前,所以 it
的结果从不指向“foo”。将两个作业移到两个 push_back
下面语句应该可以解决问题。还是需要查看it
的返回结果如下:
if (it != foo.end()) {
cout << *it << endl;
} else {
cout << "*** NOT FOUND" << endl;
}
关于c++ - 重载 << 运算符以处理指向字符串的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21200131/