We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,931 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Simulation of functions from stl::vector

0
By Lucaci Andrei on Jul 12th, 2012 6:06 pm

Here's some simulation of the basic push_back and pop_back functions from stl vectors, "inspired" by this thread: http://www.daniweb.com/software-development/cpp/threads/427912/question-about-a-simple-vector-class-template

/*
 * vect.h
 * vect.h is licensed under GNU GENERAL PUBLIC LICENSE
 *  Created on: Jul 12, 2012
 *      Author: sin
 */

#ifndef VECT_H_
#define VECT_H_
#define _SIZE 0
template <class T>
class vector{
	T* arr;
	int _size;
	int _capacity;
public:
	vector(){
		_size=_SIZE;
		_capacity=1;
		arr=new T[_capacity];
	}

	void resize(int size=-1){
		if (size==-1) size=_capacity=2*_size;
		if (size<=_size && size!=-1) return;
		T* temp_array=new T[size];
		for (int i=0;i<_size;i++){
			temp_array[i]=arr[i];
		}
		_capacity=size;
		arr=temp_array;
		delete temp_array;
	}

	void push_back(const T& elem){
		arr[_size]=elem;
		_size++;
		if (_size==_capacity) resize();
	}

    T pop_back(){
		_size--;
		T ret=arr[_size];
		return (ret);
	}

	 T operator[](int index){
		 return (arr[index]);
	 }

	 int size(){
		 return (_size);
	 }

	~vector(){
		delete arr;
	}
};
#endif /* VECT_H_ */

You don't have to define a _SIZE macro to initialize the size of the vector to zero...

If anything you should use const ints instead of #defines, but in this case just put a 0 in the code.

Also _SIZE is a reserved word under POSIX, since it begins with an underscore followed by a capital letter.

Why would anybody expect a resize() call to exist, and why would they expect it to double the size? Nobody would expect that.

Why would a resize(n) call where n is less than the current size be a no-op?

The resize function is completely broken, it assigns arr to the value of temp_array and then deletes temp_array which is the memory address arr now points to!!!

And it deletes it with the wrong delete operator! It must use delete[]!

Also push_back is broken because it writes past the end of the array.

pop_back unnecessarily copies the value before returning it.

operator[] could return the value by reference but it doesn't.

~vector uses the wrong delete operator too.

So this code is completely broken, unless you want to construct empty vectors, call size() on them, and crash the process before the vector gets destructed.

Rashakil Fol
Super Senior Demiposter
Team Colleague
2,732 posts since Jun 2005
Reputation Points: 1,153
Solved Threads: 182
Skill Endorsements: 25

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0573 seconds using 2.7MB