簡體   English   中英

overload <<運算符用於指向字符串的指針

[英]overload << operator to work with pointer to string

我正在學習使用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)

我無法cout對指針的依賴,似乎我必須重載<<運算符,但我必須重載<<運算符以使用字符串,因為我已經可以做了很奇怪

string boo = "bar"
cout<<boo;

發生了什么,我該如何解決這個問題?

我可以在GCC下編譯它,但MSVC拒絕它。 正如chris的評論所示,添加#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_back使用v1v2 向量發生變化后, v1v2可能指向過時的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM