simple array output overloading question.

Apr 4, 2017 at 6:08am
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?
Apr 4, 2017 at 6:19am
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.
Apr 4, 2017 at 6:46am
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 Apr 4, 2017 at 6:48am
Apr 4, 2017 at 10:20am
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;
}
Apr 4, 2017 at 10:32am
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 Apr 4, 2017 at 10:34am
Apr 4, 2017 at 11:16am
@gunnerfunner

SmartArray is probably an object, not a pointer.
Apr 4, 2017 at 11:29am
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 Apr 4, 2017 at 11:30am
Topic archived. No new replies allowed.