Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

stl

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!

like image 601
soulia Avatar asked Jan 26 '26 05:01

soulia


1 Answers

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.

like image 68
Charles Salvia Avatar answered Jan 27 '26 18:01

Charles Salvia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!