C++ Using proper child-class pointer - c++

basically, I want to implement document type converter. I've designed pretty straight-forward solution:
DocTypeParser : Parser will converts file into tree structure of nodes, representing different elements (headers, lists, bold texts, ...)
DocTypePrinter : Printer will deconstruct that tree back into text file
So far so good, but I came across nasty problem - The connection between tree nodes is estabilished through std::vector<Node *> and I am not sure how to determine what child class is being processed.
My demo code:
class Node
{
public:
Node()
{
}
~Node()
{
for (auto it : Leaf)
delete it;
}
Node &Add(Node *leaf)
{
Leaf.push_back(leaf);
return *this;
}
std::vector<Node *> Leaf;
};
class NodeA : public Node
{
public:
NodeA() : Node()
{
}
};
class Printer
{
public:
Printer() = default;
std::string Print(Node &n)
{
int i = 0, k = n.Leaf.size();
std::string res = "<n>";
for (; i < k; ++i)
res += Print(*(n.Leaf[i]));
res += "</n>";
return res;
}
std::string Print(NodeA &n)
{
int i = 0, k = n.Leaf.size();
std::string res = "<A>";
for (; i < k; ++i)
res += Print(*(n.Leaf[i]));
res += "</A>";
return res;
}
};
int main(int argc, const char *argv[])
{
NodeA tree;
tree.Add(new NodeA).Add(new NodeA);
Printer p;
std::cout << p.Print(tree) << std::endl;
return 0;
}
Desired result: <A><A></A><A></A></A>
Actual result: <A><n></n><n></n></A>
I pretty much understand what is the problem (vector stores Node pointers, not NodeChild pointers), but not that sure how to overcome that. dynamic_cast seems to be not-the-solution-at-all.
So finally question - is there cure for me or am I longing for the wrong design altogether?

You used type erasure wrongly. Your nodes accessed by Node* , so *(n.Leaf[i]) expression returns type Node, not NodeA.
What you do resembles visitor pattern, to recognize which class is which you have to use a virtual method in Node class and override it in NodeA, calling it with dispatcher as argument (classic visitor) or calling it from dispatcher you can recognize which instance is which.
In first case node would call the Print method and pass it *this.
This is minimal rework of your code, but I think, it needs honing\optimizing. Depends on what your actual task is, vistor might be a little too excessive.
#include <string>
#include <iostream>
#include <vector>
class Node;
class NodeA;
class AbstractPrinter
{
public:
virtual std::string Print(Node &n) =0;
virtual std::string Print(NodeA &n) =0;
};
class Node
{
public:
Node()
{
}
virtual ~Node()
{
for (auto it : Leaf)
delete it;
}
Node &Add(Node *leaf)
{
Leaf.push_back(leaf);
return *this;
}
virtual std::string Print(AbstractPrinter& p)
{
return p.Print(*this);
}
std::vector<Node *> Leaf;
};
class NodeA : public Node
{
public:
NodeA() : Node()
{
}
// if not override this, it would use Node
virtual std::string Print(AbstractPrinter& p) override
{
return p.Print(*this);
}
};
class Printer : public AbstractPrinter
{
public:
Printer() = default;
std::string Print(Node &n)
{
int i = 0, k = n.Leaf.size();
std::string res = "<n>";
for (; i < k; ++i)
res += n.Leaf[i]->Print(*this);
res += "</n>";
return res;
}
std::string Print(NodeA &n)
{
int i = 0, k = n.Leaf.size();
std::string res = "<A>";
for (; i < k; ++i)
res += n.Leaf[i]->Print(*this);
res += "</A>";
return res;
}
};
int main(int argc, const char *argv[])
{
NodeA tree;
tree.Add(new NodeA).Add(new NodeA);
Printer p;
std::cout << tree.Print(p) << std::endl;
return 0;
}

Related

Should be a virtual destructor? But how?

A program that stores a phone company's consumers data in a linked list. At the end it displays the bill for each human. I have the following codes:
class BaseTypeOfContract
{
private:
int minutePrice;
int SMSPrice;
public:
void setminutePrice(int x) { minutePrice = x; }
void setSMSPrice(int x) { SMSPrice = x; }
virtual int calculateBill(int talkedMinutes, int sentSMS) = 0;
int getminutePrice() const { return minutePrice; }
int getSMSPrice() const { return SMSPrice; }
};
class SMSBaseType : public BaseTypeOfContract
{
private:
int freeSMS;
public:
SMSBaseType(int minutePrice, int SMSPrice, int freeSMS)
{
setminutePrice(minutePrice);
setSMSPrice(SMSPrice);
setfreeSMS(freeSMS);
}
public:
void setfreeSMS(int free) { this->freeSMS = free; }
virtual int calculateBill(int talkedMinutes, int sentSMS)
{
int billedSMS = (freeSMS > sentSMS) ? 0 : sentSMS - freeSMS;
return talkedMinutes * getminutePrice() + billedSMS * getSMSPrice();
}
};
class Base : public BaseTypeOfContract
{
public:
Base()
{
setminutePrice(30);
setSMSPrice(10);
}
virtual int calculateBill(int talkedMinutes, int sentSMS) { return talkedMinutes * getminutePrice() + sentSMS * getSMSPrice();}
};
class SMSMax : public SMSBaseType
{
public:
SMSMax() : SMSBaseType(20, 5, 150) {}
};
class MobiNET: public SMSBaseType
{
public:
MobiNET() : SMSBaseType(10, 15, 25) {}
};
Client's class:
class Client
{
public:
std::string name;
std::string phoneNumber;
BaseTypeOfContract* typeOfContract;
int talkedMinutes;
int sentSMS;
Client *next;
public:
Client(){}
Client(std::string n, std::string p, int bp, int ks) : name(n), phoneNumber(p), talkedMinutes(bp), sentSMS(ks) {}
void preSetPlan(std::string s)
{
if (s == "MobiNET")
this->typeOfContract = new MobiNET();
else if (s == "SMSMax")
this->typeOfContract = new SMSMax();
else this->typeOfContract = new Base();
}
std::string getname() const { return name; }
std::string getphoneNumber() const { return phoneNumber; }
void setname(std::string n) { name = n; }
void setphoneNumber(std::string pn) { phoneNumber = pn; }
void settalkedMinutes(int bp) { talkedMinutes = bp; }
void setsentSMS(int SSMS) { sentSMS = SSMS; }
int getBill() const { return this->typeOfContract->calculateBill(talkedMinutes, sentSMS); }
};
I read the data from 2 files. First file contains the name, phone number, type of contract. Second file contains the phone number, talked minutes and sent SMS.
Client* file_read_in()
{
std::ifstream ClientData;
ClientData.open("clients.txt");
Client *first = new Client;
first = NULL;
while (!ClientData.eof())
{
std::string name, phoneNumber, typeOfContract;
ClientData >> name;
ClientData >> phoneNumber;
ClientData >> typeOfContract;
std::ifstream ClientTalkedSent;
ClientTalkedSent.open("used.txt");
while(!ClientTalkedSent.eof())
{
std::string phoneNumber2;
ClientTalkedSent >> phoneNumber2;
if (phoneNumber2 == phoneNumber)
{
int talkedMinutes, sentSMS;
ClientTalkedSent >> talkedMinutes;
ClientTalkedSent >> sentSMS;
Client* tmp = new Client(name, phoneNumber, talkedMinutes, sentSMS);
tmp->preSetPlan(typeOfContract);
tmp->next = NULL;
if (first == NULL)
{
first = tmp;
}
else
{
Client *cond = first;
while (cond->next != NULL) cond = cond->next;
cond->next = tmp;
}
}
}
ClientTalkedSent.close();
}
ClientData.close();
return first;
}
And the main:
int main()
{
Client* first = file_read_in();
while(first != NULL)
{
std::cout << first->getname() << " " << first->getphoneNumber() << " " << first->getBill() << std::endl;
first = first->next;
}
return 0;
}
My problem that I should free the allocated memory but I got on idea how. Which class' destructor should do the dirty job. I would appreciate if someone could use my code, to show how the "destructor inheritance" works.
Sorry for my bad english and thanks for the help. This site helped me alot of times, but for this problem I did not find a solution.
If you have a pointer BaseTypeOfContract* typeOfContract; that is used to point to different derived classes, then BaseTypeOfContract needs to have a virtual destructor for delete typeOfContract to work.
And as Client seems to create the objects pointed to, it also ought to be responsible for cleaning them up. Either by using delete typeOfContract; in its destructor, or by storing a smart pointer to get the work done automatically.
The other part is that each Client stores a pointer to the next Client. That seems like not the best design. In real life it is not at all like each person knowing who is the next person that buys a cell phone in the same store. :-)
You would be much better of with a container, like std::vector<Client>, that would also handle the lifetime of the Client objects.

Using Member Functions to Print Object

I have a class that contains a tree structure implemented by a vector< vector< Node > > where Node contains a bunch of attributes exposed via getters/setters.
class Tree
{
vector< vector< Node > > mGrid;
printTree(std::ostream& output = std::cout);
};
class Node
{
double property1 { return mProp1; }
double property2 { return mProp2; }
};
printTree() is currently hardwired to use property tstep:
void Tree::printTree( ostream& output )
{
...
for (unsigned t = 0; t < mGrid.size(); ++t)
{
toPrint = "";
for (unsigned state = 0; state < mGrid[t].size(); ++state)
{
toPrint += to_string_with_precision( mGrid[t][state].tstep(), 1 );
...
Is there some slick / convenient / object-oriented way of generalizing this function so that it can print out any of Node's properties (rather than only spitting out the hardwired tstep() property or essentially doing the same thing via if/then statements).
I've done things like this in C using function pointers, but this is C++ and the C++ FAQ says not to mess with pointers to member functions.
You might want template function:
class Tree
{
vector< vector< Node > > mGrid;
public:
template <typename F>
void ForEachNode(F&& f) {
int i = 0;
for (auto& v : mGrid) {
int j = 0;
for (auto& node : v) {
f(node, i, j);
++j;
}
++i;
}
}
};
Then you may do
void printTreeProp1(Tree& tree) {
tree.ForEachNode([](const Node& node, int i, int j) {
if (i != 0 && j == 0) {
std::cout << std::endl;
}
std::cout << node.property1() << " ";
});
}
1st op all you loops are ignoring the first element. vector is zero based and you are using ++t and ++state which increases the values on top of the loop. That means you are never accessing the 0th element (mGrid[0] and mGrid[t][0]).2nd, you did noy include the definition of tstep(), so we don't know what you are getting back. Assuming you want to print each dimension of your 2 dimension array, I think you have to break it to peaces. Something like this:
class Node
{
protected:
double mProp1;
double mProp2;
public:
double GetProp1(void) {return mProp1;}
double GetProp2(void) {return mProp2;}
String tStep(void) {return L"";} // add your code here
};
class NodeRow : public std::vector<Node>
{
public:
void Print(std::ostream& output)
{
iterator i;
String tStr;
for(i = begin(); i != end(); i++)
tStr += /*to_string_with_precision(*/i->tStep()/*, 1)*/;
output << tStr.c_str() << L"\r\n";
}
};
class Node2D : public std::vector<NodeRow>
{
public:
void Print(std::ostream& output = std::cout)
{
iterator i;
for(i = begin(); i != end(); i++)
i->Print(output);
}
};

Segfault Error in Custom Dictionary Class C++

So, as part of my assignment in Computer Science, which was to read tweets and put them into a custom Dictionary, I had to, you guessed it, create a dictionary. However, during testing with the dictionary, I encountered an error which I have been unable to fix, despite hours of attempted troubleshooting. I have narrowed it down, and determined that the error lies on line 144, somewhere in the statement cout<<j.get("name").getFront()->getText();, but I have been unable to determine which part of this causes issues, even when breaking it down by parts, except that it begins when I add in the ->getText(), however I heavily suspect that the problem starts earlier on.
I am sorry if I am not too specific, or if I ramble too much, I have just been having trouble with this for a while, and am beginning to get frustrated.
I understand not all the execution or style is the best, so I may ask you to refrain from leaving comments on the way things are done, unless it may directly relate to the problem at hand.
Thank you for any and all help.
/*********************************************************************************************************************
* [REDACTED] *
* CS 101-- Project 4 (Hashing Twitter) *
* This program stores Twitter posts in a hash table * *
*********************************************************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class tweet {
private:
string create_at;
string text;
string screen_name;
public:
string getCreate_at() {
return create_at;
};
string getText() {
return text;
};
string getScreen_name() {
return screen_name;
};
void setCreate_at(string c) {
create_at=c;
};
void setText(string c) {
text=c;
};
void setScreen_name(string c) {
screen_name=c;
};
};
class LinkedList {
public:
tweet* getFront() {
return top;
};
LinkedList* getNext() {
return next;
};
void setNext(LinkedList* c) {
next = c;
};
void setTweet(tweet c) {
top = &c;
};
void setTweet(tweet* c) {
top = c;
};
void insertFront(tweet c) {
LinkedList temp;
temp.setTweet(top);
temp.setNext(next);
this->setTweet(c);
this->setNext(&temp);
};
tweet* removeFront() {
tweet* temp;
temp = top;
if(next != NULL){
top = next->getFront();
if(next->getNext() != NULL)
next = next->getNext();
}
return temp;
};
private:
tweet* top;
LinkedList* next;
};
class HashTable {
private:
vector<LinkedList> store [256];//access by firstcharacter of name as index of array then search through vector linearly until find key
LinkedList getLinkedList(string c) {
vector<LinkedList> temp=store[(int)c.c_str()[0]];
for(int i =0;i<temp.size();i++) {
if(temp.at(i).getFront()->getScreen_name()==c) {
return temp.at(i); //gets list of tweets
}
};
};
bool keyExists(string c) {
vector<LinkedList> temp = store[(int)c.c_str()[0]];
for(int i =0;i<temp.size();i++) {
if(temp.at(i).getFront()->getScreen_name()==c) {
return true; //gets list of tweets
}
};
return false;
};
void insertTweet(tweet c){
if(keyExists(c.getScreen_name())){
getLinkedList(c.getScreen_name()).insertFront(c);
} else {
LinkedList temp;
temp.setTweet(c);
store[c.getScreen_name().c_str()[0]].push_back(temp);
}
};
public:
void put(tweet c) {
insertTweet(c);
};
LinkedList get(string key) {
return getLinkedList(key);
};
bool contains(string key) {
return keyExists(key);
};
void remove(string key) {
vector<LinkedList> temp=store[key.c_str()[0]];
for(int i =0;i<temp.size();i++) {
if(temp.at(i).getFront()->getScreen_name()==key) {
temp.erase(temp.begin()+i); //gets list of tweets
}
};
};
};
HashTable parser(string filename) {
//backslashes
};
int main(int argc, char *argv[])
{
tweet hello;
hello.setText("hello");
hello.setScreen_name("user");
hello.setCreate_at("10211997");
tweet heyo;
heyo.setText("heyo");
heyo.setScreen_name("name");
heyo.setCreate_at("79912101");
LinkedList jerome;
jerome.insertFront(hello);
cout<<jerome.getFront()->getText()<<endl;
jerome.insertFront(heyo);
cout<<jerome.removeFront()->getText()<<endl;
HashTable j;
j.put(heyo);
cout<<j.get("name").getFront()->getText();
}
You are getting the addresses of temporaries:
void insertFront(tweet c) {
LinkedList temp;
temp.setTweet(top);
temp.setNext(next);
this->setTweet(c); //should be &c, but c is a temporary!
this->setNext(&temp); //temp is a temporary!
};
Also, in HashTable, you need put and insertTweet to have a tweet& parameter.
Finally, still in insertTweet, you should pass the address of c to setTweet.
Note that this code is very fragile, as you will have dangling pointers as soon as the tweet objects go out of scope.

Generic Segment Tree implementation using C++ Templates

I am trying to make a generic Segment Tree Class for updates and range queries.
Instead of assuming that the elements would just be integers and the operation to be done over a range of elements would be their sum or product, i would want the user to provide the type T of the element and a function, which i named compose.
This function takes in two parameters of type T and returns a value of the same type T. This return value is the result when that desired operation is performed over range of 2 elements which i can use to perform that same operation on a range of any number of elements.
The class is as follows:
#include <functional>
template<class T>
class SegmentTree {
public:
class binary_function_unitype: public std::binary_function<T,T,T> {
public:
virtual T operator() (T arg1, T arg2) {};
};
private:
class Node {
public:
T value;
int seg_start, seg_end;
Node* left;
Node* right;
Node (T value, int seg_start, int seg_end, Node* left=0, Node* right=0) {
this->value = value;
this->seg_start = seg_start;
this->seg_end = seg_end;
this->left = left;
this->right = right;
}
};
// Not expecting the compose function to be robust enough.
T composeUtil (T arg1, T arg2) {
if (arg1!=0 && arg2!=0)
return compose(arg1,arg2);
else if (arg1!=0)
return arg1;
else if (arg2!=0)
return arg2;
}
// Creating the Segment Tree.
Node* createTree (T leaves[], int start, int end) {
// base case - leaf of tree.
if (start==end)
return new Node(leaves[start],start,start,0,0);
// general case.
int mid = start + (end-start)/2;
Node* left = createTree(leaves,start,mid);
Node* right = createTree(leaves,mid+1,end);
T retValue = composeUtil(left->value,right->value);
return new Node(retValue,start,end,left,right);
}
// Range Query helper.
T queryUtil (Node* root, int start, int end) {
int seg_start = root->seg_start, seg_end = root->seg_end;
if (seg_start>end || seg_end<start)
return 0;
else if (seg_start>=start && seg_end<=end)
return root->value;
else
return compose( queryUtil(root->left,start,end), queryUtil(root->right,start,end));
}
// Helper function for Updating the Segment Tree.
void updateUtil (Node* root, int position, T updatedValue) {
int seg_start = root->seg_start, seg_end = root->seg_end;
if(seg_start>position || seg_end<position)
return;
else if(seg_start==seg_end)
root->value = updatedValue;
else
root->value = composeUtil(root->left->value,root->right->value);
}
// Freeing the memory allocated to the Segment Tree.
void destroyTree(Node* root) {
if (root->left!=0)
destroyTree(root->left);
if (root->right!=0)
destroyTree(root->right);
delete root;
}
Node* root;
binary_function_unitype compose;
public:
SegmentTree (T leaves[], binary_function_unitype compose, int start, int end) {
this->compose = compose;
this->root = createTree(leaves, start, end);
}
T query (int start, int end) {
return queryUtil(root, start, end);
}
void update (int position, T updatedValue) {
updateUtil(root, position, updatedValue);
}
~SegmentTree () {
destroyTree(root);
}
};
When I tried to use this class, it turns out that the compose function, which I took in as a paramater is not being used, on the contrary the one from the class binary_function_unitype is being used.
I expected that the function definition from the user would override the one in class binary_function_unitype and my work would be done. But that did not happen. The program using this class is as follows:
#include <iostream>
#include "SegmentTree.h"
using namespace std;
class Compose: public SegmentTree<int>::binary_function_unitype {
public:
int operator() (int arg1, int arg2) {
return arg1+arg2;
}
};
int main()
{
int num;
cin>>num;
int arr[num];
for(int i=0;i<num;i++)
cin>>arr[i];
Compose compose;
SegmentTree<int> segTree(arr, compose, 0, num-1);
int s,e;
cin>>s>>e;
cout<<segTree.query(s-1,e-1);
return 0;
}
Can somebody tell me whats the flaw in my approach or if I misunderstood some basic concept about using inheritance or templates in C++ ?
Thanks.
The constructor takes a binary_function_unitype by value, so it will slice.

Vector Iterators Incompatible (Segmentation Fault)

I was trying to implement some Graph Algorithms so continuing by testing I received an error in GNU C++ compiler (Segmentation Fault). In Visual Studio I saw the cause is "vector iterators incompatible". But how this happens? The error is thrown in shortestPathBFS function in the line "getName()" when I try to access a field of visitor object. Visitor is an element of Vertice* queue, so it must not depend on queue iterator in my opinion. If you can explain me why, I will be appreciated.
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <string>
#include <iostream>
using namespace std;
//#define traverse(container,iterator) \
//for(typeof(container.begin()) iterator = container.begin(); iterator != container.end(); iterator++)
class Edge;
class Vertice
{
private:
string name;
vector<Edge*> incidences;
bool visited;
public:
Vertice() {name = "NULL"; visited = false;}
Vertice(string name) {this->name = name; visited = false;}
void setName(string name) {this->name = name;}
string getName() {return name;}
bool isVisited() {return visited;}
void setVisited() {visited = true;}
void setUnvisited() {visited = false;}
void connectTo(Vertice*);
void connectTo(Vertice*,int);
void printNeighbors();
vector<Vertice*> getNeighbors();
};
class Edge
{
private:
int cost;
Vertice *start,*end;
public:
friend class Vertice;
Edge() {cost = 0;}
Edge(Vertice * start, Vertice * end) {this->start = start; this->end = end;}
Edge(Vertice * start, Vertice * end, int cost)
{this->start = start; this->end = end; this->cost = cost;}
Vertice* getEnd() {return end;}
Vertice* getStart() {return start;}
};
void Vertice::connectTo(Vertice * w)
{
incidences.push_back(new Edge(this,w));
}
void Vertice::connectTo(Vertice* w,int cost)
{
incidences.push_back(new Edge(this,w,cost));
}
vector<Vertice*> Vertice::getNeighbors()
{
vector<Vertice*> temp;
for(vector<Edge*>::iterator it = incidences.begin(); it != incidences.end(); it++)
{
temp.push_back((*it)->getEnd());
}
return temp;
}
void Vertice::printNeighbors()
{
for (vector<Edge*>::iterator i=incidences.begin(); i!= incidences.end(); i++)
{
cout<<(*i)->start->getName()<<"--"<<(*i)->cost<<"--"<<(*i)->end->getName()<<endl;
}
}
class Graph
{
public:
// using set for non-comparable elements are not good
// but this is for exercising
set<Vertice *> vertices;
public:
void initGraph()
{
Vertice *v;
v = new Vertice("IST");vertices.insert(v);
v = new Vertice("ANK");vertices.insert(v);
v = new Vertice("IZM");vertices.insert(v);
v = new Vertice("BER");vertices.insert(v);
v = new Vertice("TOR");vertices.insert(v);
v = new Vertice("BEJ");vertices.insert(v);
v = new Vertice("PER");vertices.insert(v);
(*findByName("IST"))->connectTo(*findByName("ANK"),10);
(*findByName("IST"))->connectTo(*findByName("IZM"),5);
(*findByName("IST"))->connectTo(*findByName("BER"),61);
(*findByName("IZM"))->connectTo(*findByName("ANK"),3);
(*findByName("IZM"))->connectTo(*findByName("TOR"),98);
(*findByName("IZM"))->connectTo(*findByName("BER"),70);
(*findByName("BER"))->connectTo(*findByName("ANK"),59);
(*findByName("BER"))->connectTo(*findByName("TOR"),91);
(*findByName("ANK"))->connectTo(*findByName("PER"),77);
(*findByName("ANK"))->connectTo(*findByName("BEJ"),151);
(*findByName("BEJ"))->connectTo(*findByName("TOR"),48);
(*findByName("TOR"))->connectTo(*findByName("ANK"),100);
(*findByName("PER"))->connectTo(*findByName("BEJ"),162);
(*findByName("TOR"))->connectTo(*findByName("PER"),190);
(*findByName("BEJ"))->connectTo(*findByName("PER"),163);
}
set<Vertice*>::iterator findByName(string name)
{
for(set<Vertice*>::iterator it = vertices.begin(); it != vertices.end(); it++)
{
if ((*it)->getName() == name)
{
return it;
}
}
return vertices.end();
}
int shortestPathBFS(Vertice * start, Vertice * finish)
{
queue<Vertice *> q;
q.push(start);
Vertice *visitor;
while(!q.empty())
{
visitor = q.front();q.pop();
visitor->setVisited();
cout<<"BFS : "<<visitor->getName()<<endl;
if (visitor->getName() == finish->getName())
{
break;
}
for(vector<Vertice*>::iterator it = (visitor->getNeighbors()).begin(); it != (visitor->getNeighbors()).end(); it++ )
{
if (!(*it)->isVisited())
{
q.push((*it));
}
}
}
return 0;
}
void printAll()
{
for(set<Vertice*>::iterator it = vertices.begin(); it != vertices.end(); it++)
{
(*it)->printNeighbors();
}
}
};
int main(int argc, char **argv)
{
Graph g;
g.initGraph();
g.printAll();
g.shortestPathBFS(*(g.findByName("IST")),*(g.findByName("PER")));
return 0;
}
The culprit is this line in Graph::shortestPathBFS:
for(vector<Vertice*>::iterator it = (visitor->getNeighbors()).begin(); it != (visitor->getNeighbors()).end(); it++ )
The problem is that you cannot compare iterators from two different containers (even if the containers are the same type), but visitor->getNeighbors() returns a new object each time it is invoked. Consequently, it is initialized from one object then compared to an iterator from a different object.
Rewrite the loop as:
vector<Vertice*> neighbors = visitor->getNeighbors();
for(vector<Vertice*>::iterator it = neighbors.begin(); it != neighbors.end(); ++it)
{
if (!(*it)->isVisited())
{
q.push((*it));
}
}