Changes on elements in a Vector

Hi, I've got a problem using the Vector-class. When using it to implement a version of Dijkstra's algorithm I ran into reference-issues, so I tried this out:

cout << myVector[0].getColor();
myVector[0].setColor(myVector[0].getColor()+1);
cout << " " << myVector[0].getColor();
getColor and setColor are simple getter and setter for an integer-value. The above listed code results in the following output: "1 1", which isn't exactly what I'd like to happen. Can someone help me please? What do I have to change in order to get "1 2" put out?
Hi,

Can you post the code from the "getter" and "setter" so we can see what you are doing in there?
Last edited on
Of course but that's really harmless:

int getColor(){
return color;
};
void setColor(int c){
color=c;
};
Have you tried passing though some different values to setColor()?

eg.
cout << myVector[0].getColor();
myVector[0].setColor(7);
cout << " " << myVector[0].getColor();

See what happens. Maybe this will help you find where the problem is..
Last edited on
This doesn't work either. On top of that, I found another strange thing. Consider the following two lines:

cout << *(c->vertices.at(0)) << endl << g->getVertices().at(0) << endl;
cout << *(c->vertices.at(0)) << endl;

The first line prints the excepted result ("Vertex 001 with label A
Vertex 001 with label A).
It also does it repeatedly. The second line doesn't do what it's intended to do at all. It prints out "Vertex " and then doesn't print out anything anymore, even if I put the working line after it. I'm quite confused as I don't understand why the first line works and the second one doesn't. If it helps: g is a Graph and c is a Component, which holds certain vertices of g in its member vertices. These are the vectors I meant when I wrote "myVector" above.
I try to avoid the subscript operator whenever iterators are available. I realize Dijkstra's algorithm indexes into arrays, and I seem to recall they were arrays of distance values...
Anyway, I hope this helps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class myClass {
private:
	int color;
public:
	myClass() {color=0;}
	~myClass(void) {}
	void setColor(const int &c) {color=c;}
	int getColor() const {return color;}
};

int main()
{
	vector<myClass> myVector;
	myClass mc;
	mc.setColor(1);
	myVector.push_back(mc);
	// Your code. Output:  1 2
	cout << myVector[0].getColor();
	myVector[0].setColor(myVector[0].getColor()+1);
	cout << " " << myVector[0].getColor();
	// My code. Same results
	vector<myClass>::iterator iter=myVector.begin();
	cout << (*iter).getColor();
	(*iter).setColor((*iter).getColor()+1);
	cout << " " << (*iter).getColor();
	return 0;
}

Topic archived. No new replies allowed.