c++ - 重载 << 运算符以处理指向字符串的指针

标签 c++ algorithm debugging find overloading

我正在学习使用 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>解决问题。

然后您的程序在运行时崩溃了。您分配给了 v1v2在您将值分配给 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/

相关文章:

c++ - 使用模板时,是否可以确定左值的类型?

c++ - 正确删除EGL Opengles 2.0

c++ - 在 cuda 内核中声明 CPP 对象

algorithm - 保留(或排序)前 10 名最畅销产品的最有效方法是什么?

python - 优化存储在 SQLite 中的数据 - 如何加入多个联系人?

iphone - 类 _NSZombie__GEOTileKeyWrapper 在两者中都实现了 ??和 ??。将使用两者之一。哪一个是未定义的

iphone - 有没有办法对 Xcode 中的 iPhone 调试器控制台显示进行颜色编码?

c++ - 重载 * 乘法运算符两次作为成员函数?

perl - 为什么这种魔术 Perl 内部变量的解决方法有效?

algorithm - Locality Sensitive Hashing 可以用于动态数据吗?