Reputation: 101
I'm trying to use a vector iterator to print out all of the elements in a vector. I've looked up similar questions but the solutions posted don't seem to be working for me. Here's the code:
void printPerms()
{
for(vector<process>::iterator it = allProcesses.begin(); it != allProcesses.end(); it++)
{
for(int i = 0; i < numResourceTypes; i++)
{
cout << (static_cast<process*>(*it).need) << (static_cast<process>(*it)).allocated <<endl;
}
}
}
And the errors I am getting, which I don't know how to fix:
error C2440: 'static_cast' : cannot convert from 'process' to 'process *' No user
defined-conversion operator available that can perform this conversion, or the operator
cannot be called
error C2228: left of '.need' must have class/struct/union
Upvotes: 1
Views: 1568
Reputation: 20403
The problem is that *it
is of type process
, you might try getting its address before casting by changing
(static_cast<process*>(*it).need)
to
((static_cast<process*>(&(*it)))->need)
However, it might be simpler to do it->need
By the way, if you are just printing (and not modifying the vector
contents), then it is recommended to use const_iterator
instead of iterator
.
Upvotes: 1
Reputation: 1004
Try...
void printPerms()
{
for(vector<process>::iterator it = allProcesses.begin(); it != allProcesses.end(); it++)
{
for(int i = 0; i < numResourceTypes; i++)
{
cout << it->need << it->allocated << endl;
}
}
}
I don't know what exactly is going wrong, nor do I see why you need to use static_cast
, however you should be able to access those member variables regardless using the ->
operator.
De-referencing an iterator gives you its value (in this case, the process
), with no need for a cast.
Upvotes: 6