Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* in class code
- 03/26/2012
- vector
- */
- #include <iostream>
- #include <vector>
- using namespace std;
- class Vector{ // type is the pointer to the first element
- public:
- Vector() : theSize(0), theCapacity(1), data(new int[theCapacity]){}
- explicit Vector(size_t initialSize) :
- theSize(initialSize), theCapacity(initialSize), data(new int[theCapacity])
- {
- for (size_t i = 0; i < initialSize; ++i) data[i] = 0;
- cerr << "Vector()\n";
- }
- // system provided default constructor does nothing
- // garbage values..
- //methods:
- //size
- size_t size() const { return theSize;}
- void push_back(int n){
- if (!theSize == theCapacity){
- theCapacity*=2;
- int* tempData = new int[theCapacity];
- for (size_t i = 0; i < theSize; ++i){
- tempData = data[i];
- }
- delete [] data; // tell the sytem that we are freeing up an array
- data = tempData;
- }
- data[theSize] = n;
- ++ theSize;
- //data[theSize ++];
- }
- //v.operator[](i)
- int operator[](size_t index) const {return data[index];}
- int& operator[](size_t index){return data[index];}
- // copy control
- // destructor
- -Vector() {delete [] data;}
- // copy constructor
- Vector(const Vector& rhs){
- // Mionr bookkeeping
- theSize = rhs.theSize;
- theCapacity = rhs.theCapacity;
- // Allocate the array
- data = new int[theCapacity];
- // copy over the data
- for (size_t i = 0; i < theSize; ++1){
- data[i] = rhs.data[i];
- }
- }
- // assignment operator
- Vector& operator =(const Vector& rhs){
- //0. self-assignment
- //if(rhs == * this)
- if (&rhs != this){
- //1. free up
- delete [] data;
- // Mionr bookkeeping
- theSize = rhs.theSize;
- theCapacity = rhs.theCapacity;
- // Allocate the array
- data = new int[theCapacity];
- // copy over the data
- for (size_t i = 0; i < theSize; ++1){
- data[i] = rhs.data[i];
- }
- }
- //2. allocate
- data = new int[theCapacity];
- //3. copying the data
- for (size_t i = 0; i < theSize; ++1){
- data[i]=rhs.data[i];
- }
- // * this = Vector(rhs);// NOOOOO!!
- // 4. return yourself
- return *this;
- }
- void pop_back(){
- if (size_t > 0) -- theSize;
- }
- void clear{ the size = 0;}
- private:
- size_t theCapacity;
- int* data;
- size_t theSize;
- // p[i] means *(p+i)
- // pointer arithmetic
- };
- int main(){
- Vector v;
- cout << v.size() << endl;
- v.push_back(17);
- v.push_back(45);
- v.push_back(53);
- v.push_back(78);
- for (size_t i = 0; i < v.size(); ++i){
- cout << v[i] << endl;
- //v.operator[](i)
- }
- v[2] = 100;
- Vector anotherVector(v);
- // Vector anotherVector = v;
- // 1) pass by value
- // 2) return by value
- // 3) initialization
- v.pop_back();
- v = 7;
- v = vector(7);
- }
Add Comment
Please, Sign In to add comment