use*_*504 3 c++ stl stl-algorithm
我的源代码非常简单:
#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);
}
Run Code Online (Sandbox Code Playgroud)
那么为什么我会收到编译器错误:
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>'
Run Code Online (Sandbox Code Playgroud)
集合"s"只是一组字符串,没有任何常量.
您需要为set_difference 使用插入器:
set_difference(S->begin(),S->end(),T->begin(),T->end(),std::inserter(*s, l))
Run Code Online (Sandbox Code Playgroud)
基于Neil Kirk的评论,编写此代码的"异常安全"方式将是:
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));
Run Code Online (Sandbox Code Playgroud)
在现代C++中,几乎不存在需要使用的情况new.如果你确实需要动态分配,你应该使用unique_ptr或shared_ptr.
| 归档时间: |
|
| 查看次数: |
398 次 |
| 最近记录: |