【问题标题】:VS 2010 compiler error "c2678 no operator found that converts const std::string", but nothing is declared constVS 2010 编译器错误“c2678 no operator found that converts const std::string”,但没有声明为 const
【发布时间】:2014-04-04 19:16:25
【问题描述】:

我的源代码非常简单:

#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”只是一组字符串,没有任何常量。

【问题讨论】:

  • 你需要 back_inserter for l
  • 不要“新建”STL 数据结构。 C++ 不是 Java。你只需要set&lt;string&gt; S;就可以开始使用了。

标签: c++ stl stl-algorithm


【解决方案1】:

您需要为 set_difference 使用inserter

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

基于 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));

在现代 C++ 中,几乎从来没有需要使用 new 的情况。如果您确实需要动态分配,您应该使用unique_ptrshared_ptr

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 2019-04-20
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多