Simulation of functions from stl::vector

Lucaci Andrew 0 Tallied Votes 495 Views Share

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_ */
Rashakil Fol 978 Super Senior Demiposter Team Colleague

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.