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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With