【问题标题】:transform algorithm gives "binary '=' no operator which takes left-hand operand.." [duplicate]变换算法给出“二进制'='没有接受左操作数的运算符..” [重复]
【发布时间】:2015-05-30 17:26:55
【问题描述】:
pair<CDrug, pair<unsigned,double>> expirednull(pair<CDrug,
pair<unsigned,double>> temp){
    if (temp.first.isValid() == false)
        temp.second.first = 0;
    return temp;
}

string checkForExpiredDrugs() {
    stringstream s;
    vector<CDealer>::iterator it1;
    map<CDrug, pair<unsigned, double>> d;
    map<CDrug, pair<unsigned, double>>::iterator it2;
    //transform algorithm
    for (it1 = this->m_dealers.begin(); it1 != this->m_dealers.end(); it1++) {
        s << "Dealer: " << it1->getCompany() << " " << it1->getRepresentative() << " " << it1->getTelephone() << endl;
        d = it1->getDrugs();
        transform(d.begin(),d.end(),d.begin(),expirednull);
        for (it2 = d.begin(); it2 != d.end(); it2++) {
            if (it2->first.isValid() == false) {
                it2->second.first = 0;
                s << "Expired: " << it2->first << endl;
            }
        }
        it1->setDrugs(d);
    }
    return s.str();
}

每当我运行程序时,它都会给我以下错误 ->

错误 7 错误 C2678:二进制“=”:未找到采用“const CDrug”类型左侧操作数的运算符(或没有可接受的转换)

【问题讨论】:

  • 我认为这是 compiler 错误,而不是 runtime 错误。它指的是哪一行?

标签: c++ assignment-operator stdmap


【解决方案1】:

这是因为地图元素实际上是: pair&lt; const CDrug, ... &gt; 不是pair&lt; CDrug, ... &gt;

它们的键类型是 const,因为更改地图现有元素中的键会导致麻烦。 (它会使元素未排序,从而破坏一些地图不变量)。

因此,您的转换函数返回的对象无法分配给地图元素 => 编译失败。

此外,您不能在地图上使用转换,因为您不能分配给地图迭代器(因为键是 const)。 因此,您应该改用 for_each,如此处相关问题所述:how to apply transform to a stl map in c++

类似:

void expirednull(pair<const CDrug, pair<unsigned,double> > & temp)
{
    if( temp.first.isValid == false )
        temp.second.first = 0;
}

map< CDrug, pair<unsigned,double> > d;
for_each(d.begin(),d.end(),expirednull);

【讨论】:

  • 是的,我明白这一点,但你建议我怎么做?如何使转换算法在我的情况下可用?
  • @КристиянКостадинов 使用pair&lt; const CDrug, ... &gt;而不是pair&lt;CDrug, ... &gt;
  • 已经试过了,还是一样的错误
  • 我通过澄清您应该使用 for_each 而不是 transform 来改进答案
  • @Guillaume 谢谢,这解决了我的问题!
猜你喜欢
  • 1970-01-01
  • 2012-07-23
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 2014-05-02
相关资源
最近更新 更多