Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

deleting a vector

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Hi everybody,
Do you think that following sample is all right?

Code:
#include <vector>

typedef std::vector< int* > IntVector;

IntVector giveMeTheVector()
{
	IntVector vec;
	for ( int i=0; i<1000; ++i )
		vec.push_back( new int( i ) );

	return vec;
}

int main()
{
	IntVector vec = giveMeTheVector();

	for ( IntVector::iterator it = vec.begin(); it != vec.end(); ++it )
		delete *it;

	return 0;
}
 
Well, the code is not incorrect. OTOH, I can't image why you would allocate a vector<int*> rather than just a vector<int> which you can do like this:

vector<int>vi(1000);

Your code requires twice as much space and a thousand heap allocations and deletes, not to mention being considerably slower. Of course, if it was some struct or class object instead of int it would make more sense.

:) Hope that this helped! ;-)
 
Well, I think it's all right. Anyway I wouldn't make it that way. :-V
It's easier to use a reference in a function call...
giveMeTheVector( IntVector& vec )
 
Yeah, well, this is a good point; when you return your whateverVector the entire vector has to be copied once, conceivably twice; it would be a lot more efficient to pass your mainline vec as a reference and have giveMeTheVector() assign to it directly, rather than to a temporary. :) Hope that this helped! ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top