//declared my vector as

vector<candidate> vecList;    //pretty standard stuff

//do some looping, gather info

vecList.push_back(candidate(name,voteCount));

candidate is my class name. So instead of passing an object to push_back, I pass my class name using an overloaded construtor and it works just fine. Upon further investigation, I used an iterator to loop through and display each object, and it properly stores the information, but here comes the curveball.... each element of my vector is stored at the same memory address. Anyone know why?

Can you please post a more complete example?

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class candidate
{
	public:

		candidate(string name, int voteCount)
		{
			lastName = name;
			votes = voteCount;
		}

		string lastName;
		int votes;
		double percentVotes;
};

int main()
{
	vector<candidate> vecList;

	int totalVotes = 0;

	for(int i = 0; i < 5; i++)
	{
		string name;
		int voteCount;

		cout << "\nCandidate " << i+1 << " Name: ";
		getline(cin, name);
		
		cout << "\nCandidate " << i+1 << " Votes: ";
		cin >> voteCount;
		cin.ignore();

		totalVotes += voteCount;

		vecList.push_back(candidate(name,voteCount));
	}

	system("cls");

	
	vector<candidate>::iterator n;
	for(n = vecList.begin(); n != vecList.end(); n++)
	{
		double percent = 0;

		cout << n->lastName << "    " << n->votes << "    " << ;
	}	
	

	cin.ignore();
	cin.get();

	return 0;
}

Ive changed the iterator loop because I am working on an assignment, but ya.

Edit: Heres a picture of the output when I use the iterator to loop teh address

http://yfrog.com/7d44308929j

Okay, that's not helpful. I wanted to see the actual loop that prints an address, not something completely different that works.

vector<candidate>::iterator n;
for(n = vecList.begin(); n != vecList.end(); n++)
{
cout << &n << endl;

cout << n->lastName << endl;   //to make sure it is going to the next element

}

This was how i set it up. It went to each new object which I verified by outputting the elements lastName variable.

>cout << &n << endl;
As I suspected, you're printing the address of the iterator object. You want to print the referenced object instead, which can be done by dereferencing the iterator first:

cout << &*n << endl;

>cout << &n << endl;
As I suspected, you're printing the address of the iterator object. You want to print the referenced object instead, which can be done by dereferencing the iterator first:

cout << &*n << endl;

Ohh... that makes sense. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.