开发者

Printing Vector on Console

I have a vector of type template class and I am trying to print it, but getting a weird error.

Here is my class:

template <typename VertexType, typename EdgeType> class Vertex{
开发者_开发技巧private:
    typedef std::vector<std::pair<int, EdgeType> > VertexList;
    std::vector<Vertex<VertexType, EdgeType>> Vertice;

public:
    void Add(Vertex);
};

Add Method and Print Statement:

template <typename VertexType, typename EdgeType> void Vertex<VertexType, EdgeType> ::Add(Vertex v)
{
    int count = 5;
    //std::vector<string>temp;

    for(int i=0; i<count; i++)
    Vertice.push_back(v);

    for(int i=0; i<Vertice.size(); i++)
        cout<< Vertice[i] <<endl;
}

Main() Method:

int main()
{
    Vertex<std::string, std::string> v1;

    v1.Add(v1);

    std::getchar();
}

Error am getting is:

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Vertex' (or there is no acceptable conversion)


You aren't defining an operator << anywhere. You should define it like this out of your class :

template <typename VertexType, typename EdgeType>
std::ostream& operator << (std::ostream& out, const Vertex<VertexType,EdgeType>& v);
// implementation
template <typename VertexType, typename EdgeType>
std::ostream& operator << (std::ostream& out, const Vertex<VertexType,EdgeType>& v) {
    // print whatever you want that represents your vertex

    // please don't forget to return this reference.
    return out;
}

Also, having a class with a vector of instances of it inside is a call for trouble. Remember that "vector<Vertice<VertexType,EdgeType> >" is an array of instances, not an array of references. If you want a array of 'references' to Vertex, use an array of pointers.

And consider using boost's graph library instead of redefining yet another one and coming to all pitfall associated with graphs (like memory management for instance). The boost library also have some useful algorithms that you could want to use..


Well, implement template <class V, class E> std::ostream& operator<<(std::ostream& os, const Vertex<V,E> &vertex) as a static friend of Vertex. It's pretty much what the compiler tells you...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜