No Overloaded operator= showing in algorithm.cpp

386 views Asked by At

I am working with set_union (included in algorithm.cpp) and sets in the STL library.

My sets hold objects of a custom class Vertex in which I have overloaded the operator=

Here is the Vertex class:

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;
    }
};

The problem resides in the following lines, included in the method of a different class.

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;
        }
    }

That code generates a compile error in algorithm.cpp, more specifically in the code of set_union where it states that there is no viable overloaded operator= for two objects of type 'InputIterator'.

Here is the compiler error location:

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;
}

What am I missing here?

1

There are 1 answers

1
john On BEST ANSWER

Apart from the utterly bugged Vertex::operator= (which can just be deleted) the reason for your error is that you need to wrap unionSet in an inserter.

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

Functions like set_union overate in 'overwrite' mode, that is they overwrite existing elements of the container you are writing to. If you want to add elements to an empty container you must use an adapter like inserter.