I've been struggling with a simple program to help me understand the vector-pointer relationship; so far so good, but I've hit a snag.
As seen below, I'm passing a vector to the 'showem' function as a pointer. The function simply prints out the entire vector just fine (as it's supposed to), but for some reason the compiler complains when I try to use the 'size()' function inside 'showem'.
void showem(vector<int>*temp, int sz)
{
for (int n{}; n < sz; n++)
{
cout << "Element [" << n << "] has a value of " << temp->at(n) << endl;
}
}
int main()
{
srand(static_cast<unsignedint>(time(NULL)));
vector<int>numbers;
int choice{};
cout << "Enter number of elements to create:";
cin >> choice;
initialize(&numbers,choice);
showem(&numbers, numbers.size());
return 0;
}
The issue is, the code I wanted to use in the 'showem' for-loop was:
for (int n{}; n < temp.size(); n++)
This would save me the trouble of having to send an extra variable (sz) to the function.
When I try to use the size() function inside 'showem', the compiler tells me it "must have class type" and "left of '.size' must have class/struct/union"
In main(), the size() function works just fine.
Any help would be appreciated.
Cheers!
Because you are dealing with the pointer variable of the vector, you need to dereference the pointer when you call the member function.
It didn't work because you were trying to call the member function of temp as if temp was the actual object. It's not. It only has the address of the object.
This is normally how you call the member function of an object.
obj.size();
But, if you have a pointer that points to the address of an object, you need to dereference and then call the member function.
(*temp).size(); // You need the parenthesis because . has higher precedence than *
It looks ugly, doesn't it. So C++ provides a better way to write it.
temp->size(); // This is same as (*temp).size(); but it looks much better.
Remember the point of the work is to use pointers..size() will give you the size of numbers in your case, but in the showem function you are trying to use .size() on a pointer. It does not work that way.
Line 17 passes the size of the vector to the function and there it works correctly.
mpark, thanks for that. I had been plugging away at pointers all day, and it never occurred to me to dereference in the 'addem' function. The confusion came from the syntax in the function arguments; my bad.