simple array output overloading question.

In my cmpt notes, there is array cout overloaded, ostream. Its job is to just simply print an array. They used for loop to print the array except the last element of the array. Later, they put a condition that if the array size is > 0, then only print the last element. My question is, why is that?
First, they print all elements, but the index starts from 0, so if the last index is n-1, then there are indeed n elements.

Second, what would you print if the array didn't had any elements? So, that condition makes sense.
1
2
3
4
5
6
7
8
9
10
ostream& operator << (ostream& outputStream, const SmartArray& L)
{
	outputStream << "[";
	for(int i=0; i< L.getSize() -1; i++)
		outputStream << L[i] << ", ";
	if(L.getSize() > 0)
		outputStream << L[L.getSize() -1];
	outputStream << "]";
	return outputStream;
}


My question is, why the condition is on the last element. They could have put it first for more efficient code. I believe.
Last edited on
The reason is this:

outputStream << L[i] << ", ";

The comma shouldn't appear after the last element.

Another approach would be this:
1
2
3
4
5
6
7
8
9
10
11
12
ostream& operator << (ostream& outputStream, const SmartArray& L)
{
	outputStream << "[";
	for(int i=0; i< L.getSize(); i++)
	{
		if(i > 0)
			outputStream << ", ";
		outputStream << L[i];
	}
	outputStream << "]";
	return outputStream;
}
OP: I'd also be interested to know how you're retrieving the size of the array from, seemingly, just the pointer. Can you share the getSize() function? Thanks
edit: or perhaps L is written out by hand?
 
 int L[] = {1, 2, 3, 4, 5, 6};
Last edited on
@gunnerfunner

SmartArray is probably an object, not a pointer.
coder777 - yeah, i think you're right, that's what it could be ... edit: indeed the way it's being passed to the function seems to suggest that even more strongly
Last edited on
Topic archived. No new replies allowed.