重载运算符<<使用指向字符串的指针

overload << operator to work with pointer to string

本文关键字:lt 字符串 指针 运算符 重载      更新时间:2023-10-16

我正在学习使用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,因此it的结果永远不会指向"foo"。将两个赋值移到两个push_back语句的下方应该可以解决问题。您仍然需要检查it的返回结果,如下所示:

if (it != foo.end()) {
    cout << *it << endl;
} else {
    cout << "*** NOT FOUND" << endl;
}

添加#include <string>,你应该没问题。

此外,请确保使用 C++11 进行编译(不是某些编译器的默认编译器)。

另外,为了安全起见,请在push_backv1v2v1v2可以在矢量更改后指向过时的位置。