![](/img/trans.png)
[英]Why does it not work to overload “operator <<” on std::string?
[英]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>
解決了這個問題。
然后你的程序在運行時崩潰了。 在將值賦給向量之前,您已分配給v1
和v2
,因此it
的結果從不指向“foo”。 將兩個賦值移動到兩個push_back
語句下面應該可以解決問題。 你仍然需要檢查的返回結果it
如下:
if (it != foo.end()) {
cout << *it << endl;
} else {
cout << "*** NOT FOUND" << endl;
}
添加#include <string>
你應該沒問題。
另外,請確保使用C ++ 11進行編譯(不是某些編譯器的默認值)。
另外,為了安全起見,請在 push_back
值后使用v1
和v2
。 向量發生變化后, v1
和v2
可能指向過時的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.