Reputation: 43
I'm new to this website and a bit new in programming. I'm using vector for the first time and I want to print content of it but I'm getting addresses instead of normal words. I don't know how to do that in other way than this.
My vector:
vector<Component*> vect;
and my code for printing:
void Frame::print() {
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << endl;
}
Upvotes: 0
Views: 1429
Reputation: 4010
You are storing pointers in your vector. The value of a pointer is a memory address, therefore you are seeing addresses in your output. You need to dereference the pointers to access the actual Component
objects:
void Frame::print()
{
for (int i = 0; i < vect.size(); i++)
{
Component *component = vect[i];
cout << *component << endl; // <-- not the extra '*'
}
}
In order for this to work, an operator<<
overload for Component
is also required:
ostream& operator<<(ostream &out, const Component &comp)
{
// print comp values to out as needed...
return out;
}
Recommended reading:
You also need to study up on pointers and references in general.
Upvotes: 3
Reputation: 880
vect is a vector (aka a lump of contiguous storage) of Component * (aka Component pointers) that is it's a chunk of memory with addresses of other chunks of memory which the compiler will treat as a Component class object. Printing those addresses via cout will just give you a big list of meaningless numbers.
What I suspect you want to do is probably not store a vector of Component pointers at all and just store a vector of Components. It's frowned upon in C++ these days to store raw pointers unless you know exactly what you are doing. If you really do want pointers you should use a vector of std::unique_ptr and std::make_unique.
Once you start trying to print Components rather than addresses of them you will most likely see that there is no << operator for Component. You will need to write one. Something like
std::ostream& operator<<(std::ostream &stream, const Component&component)
{
stream << component.string_member;
return stream;
}
Upvotes: 1