二进制'=':没有找到哪个运算符采用'const Thing'类型的左手操作数

问题描述 投票:0回答:1

我读了重复,但真的没有帮助我。

我正试图达到下一个行为。有一个由{Thing, set < Thing >}对组成的向量我想要{Thing, newSetOfThing < Thing >}的最终结果,其中'newSetOfThing'是应用于向量中的每个其他集合的差异,但他自己。差异意味着拥有所有值,但包含在其他集合中。我正在使用std::set_difference

给出一个更接近数字的例子。

vector = {[1, {3,4,5,7}], [2,{1,3,9}], [3, {1,2,12}]};

==>

vectorResult = {[1, {4,5,7}], [2, {9}], [3, {2,12} } 

然后我的代码看起来像这样:

class Thing {
public:
    Thing () {
    };
    ~Thing () {};
    int position; //id
    bool operator<(const Thing &Other) const;
};
bool Thing::operator<(const Thing &Thing) const
{
  return(Other.position<position);
}

//The original vector
vector<pair<Thing, set<Thing>>> pairWithSet;

// I fill vector here [...]

// variable I define to store partial results
set<Thing> differenceResult;
// Vector I want to fill for results
vector<pair<Thing, set<Thing>>> newPairWithSet;

// Operation 
for (pair<Thing, set<Thing>> currentPair : pairWithSet){
    Thing currentThing= currentPair.first;
    differenceResult = currentPair.second;
    for (int i=0; i<pairWithSet.size();i++) {
       if (pairWithSet[i].first.position != currentThing.position) {
    set_difference(differenceResult.begin(),
                   differenceResult.end(),
                   pairWithSet[i].second.begin(),
                   pairWithSet[i].second.end(),
                   differenceResult.begin());
}
         newPairWithSet.push_back(pair<Thing, set<Thing>>(currentThing, differenceResult));
}

我解释了我的目标,你有一个点从哪里去,但最后我认为问题更多地与我使用set_difference操作有多么错,我不能直接指定'Thing'。所以set_difference无法检查它们是否相同。因为错误是

binary'=':找不到带有'const Thing'类型的左手操作数的运算符(或者没有可接受的转换

我说因为可能还有其他错误可以达到行为,因为在我解决运算符问题之前我仍然无法调试。

我的问题是我是否需要声明'='操作以及如何操作。或者如果我错过了某些东西,我需要以另一种方式表现。

我可以确保问题是当我使用set_difference时,如果我评论这部分编译器执行任务:

 set_difference(differenceResult.begin(),
                       differenceResult.end(),
                       pairWithSet[i].second.begin(),
                       pairWithSet[i].second.end(),
                       differenceResult.begin());

我认为是因为最终它试图对const执行赋值(因为std::pair声明?),因为它说错误(然后显然编译器不知道如何操作)。所以我还不清楚如何执行递归set_difference。

c++ vector set std-pair set-difference
1个回答
1
投票

set_difference将结果写入其第5个参数所指的位置。你传递differenceResult.begin()有什么不对,因为beginset总是返回const迭代器。如果目标是const迭代器指向的对象,则不能执行写操作。

如果你想通过Thing算法将set对象存储到set_difference,你可以使用std::inserter

        set<Thing> res;  // CREATE EMPTY SET
        set_difference(differenceResult.begin(),
          differenceResult.end(),
          pairWithSet[i].second.begin(),
          pairWithSet[i].second.end(),
          std::inserter(res,res.begin())); // CREATE INSERT_ITERATOR WHICH INSERTS THINGS INTO RES

然后你可以将res复制到newPairWithSet

© www.soinside.com 2019 - 2024. All rights reserved.