error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::vector<_Ty> *' (or there is no acceptable conversion)

17,712

Solution 1

The new operator returns a pointer type, but your member variable neighbors is not a pointer. So you're assigning a pointer (the result of new) to a non-pointer type. Your neighbors variable needs to be a pointer: vector<T>* neighbors.

But I think you're probably misunderstanding the use of new here. You probably shouldn't even use a vector pointer at all. Just remove the line neighbors = new vector<T>(). The vector object will be automatically initialized and ready for use.

In C++, the new keyword allocates and initializes objects on the heap, which then must be freed later using delete. It's preferable to avoid the new keyword by simply initializing the object as an automatic variable, like:

vector<T> neighbors;

This way, you don't have to worry about memory management, and the vector object will automatically be destroyed when it goes out of scope.

Solution 2

vector<T>  neighbors;
neighbors = new vector<T>();

neighbours is not a pointer.

The whole point of using vectors is not managing the memory explicitly. In fact in your node constructor, neighbours is default-initialized, so just don't initialize. Your constructor may look like this:

Node(){}

So you can just omit it :)

Share:
17,712
soulia
Author by

soulia

Business owner, developer, adjunct prof, and still growing.

Updated on June 25, 2022

Comments

  • soulia
    soulia almost 2 years

    I've got the following when building a graph.

    #include <vector>
    using namespace std;
    
    template<class T>
    class Node
    {
    private:
      T data;
      Node<T> *link;
      vector<T>  neighbors;
    public:
      Node(){neighbors = new vector<T>();};
    };
    
    int main()
    {
      Node<int> n;
      return 0;
    }
    

    ... which returns the error C2679: binary '=': no operator found...

    I'm using VS2010. What's wrong? Thanks!

  • soulia
    soulia over 13 years
    Rookie error... That's why it's good to step away and get a coffee. Thanks, Charles!