无重载运算符=显示在算法.cpp中

No Overloaded operator= showing in algorithm.cpp

本文关键字:算法 cpp 显示 重载 运算符      更新时间:2023-10-16

我正在使用set_union(包含在algorithm.cpp中)和STL库中的集合。

我的集合包含自定义类Vertex的对象,在该类中我重载了运算符=

这是Vertex类:

class Vertex {
public:
    City city;
    bool wasVisited;
    Vertex() {};
    Vertex(City c) {city = c; wasVisited = false;}
    double getWeightToVertex(Vertex v) {return city.getWeightWith(v.city);}
    Vertex& operator=(const Vertex&v) {
        if(this == &v)
            return *this;
        city = v.city;
        return *this;
    }
};

问题存在于以下行中,这些行包含在另一个类的方法中。

for(int i=0; i<nEdges; i++) {
        Edge e = edges[i];
        Vertex start = vertexList[e.start];
        Vertex end = vertexList[e.end];
        if(sets[e.start].find(vertexList[e.end]) == sets[e.start].end()) { // The two vertices do not belong to the same set
           //Add the edge to our MST
            MST[nValidEdges] = e;
            nValidEdges++;
            //Get the union of vertex sets and insert it
            //in the corresponding place in the dynamic array
            set<Vertex> unionSet;
            set_union(sets[e.start].begin(), sets[e.start].end(), sets[e.end].begin(), sets[e.end].end(), unionSet.begin());
            sets[e.start] = unionSet;
        }
    }

该代码在algorithm.cpp中生成编译错误,更具体地说,在set_union的代码中,它声明对于"InputIterator"类型的两个对象没有可行的重载运算符=。

以下是编译器错误位置:

template <class _InputIterator, class _OutputIterator>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
__copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
{
    for (; __first != __last; ++__first, ++__result)
        *__result = *__first; //Error Here: No Viable Overloaded '='
    return __result;
}

我在这里错过了什么?

除了完全错误的Vertex::operator=(可以删除)之外,错误的原因是您需要将unionSet包装在插入器中。

set_union(sets[e.start].begin(), 
    sets[e.start].end(), 
    sets[e.end].begin(), 
    sets[e.end].end(), 
    inserter(unionSet, unionSet.begin()));

set_union这样的函数在"覆盖"模式下覆盖,也就是说,它们覆盖要写入的容器中的现有元素。如果要将元素添加到空容器中,则必须使用类似适配器的插入器。