2014-04-04 29 views
3

我的源代碼是一樣簡單,因爲它得到:VS 2010編譯器錯誤「c2678沒有操作員發現,轉換常量的std :: string」,但沒有被聲明爲const

#include <set> 
#include <string> 
#include <functional> 
#include <algorithm> 
#include <iterator> 

using namespace std; 

void test() { 
    set<string> *S = new set<string>; 
    S->insert("hi"); 
    S->insert("lo"); 
    set<string> *T = new set<string>; 
    T->insert("lo"); 
    set<string> *s = new set<string>; 
    set<string>::iterator l=s->begin(); 
    set_difference(S->begin(),S->end(),T->begin(),T->end(),l); 
} 

那麼,爲什麼我得到一個編譯器錯誤:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(4671): error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::basic_string<_Elem,_Traits,_Ax>' 

集合「s」只是一組字符串,沒有const常量。

+0

你需要back_inserter爲l –

+4

不要「新」STL數據結構。 C++不是Java。所有你需要的是'設置 S;'你可以開始使用它。 –

回答

8

您需要使用一個inserter爲set_difference:

set_difference(S->begin(),S->end(),T->begin(),T->end(),std::inserter(*s, l)) 

大廈從尼爾·柯克註釋的「異常安全」的方式編寫這些代碼將是這樣的:

set<string> S; 
S.insert("hi"); 
S.insert("lo"); 
set<string> T; 
T.insert("lo"); 
set<string> s; 
set<string>::iterator l=s.begin(); 
set_difference(S.begin(),S.end(),T.begin(),T.end(),std::inserter(s, l)); 

在現代的C++幾乎不存在你需要使用new的情況。如果你確實需要動態分配,你應該使用unique_ptrshared_ptr

相關問題