Output problem in template class
Mar 5, 2014 at 1:50pm UTC
Whats problem here? I am getting garbage outputs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include <iostream>
using namespace std;
template <class T> class vector {
T* v;
int default_capacity;
int initial_capacity;
int counter;
public :
vector()
{
default_capacity=1;
v = new T[default_capacity];
counter=1;
}
vector(int s)
{
initial_capacity=s;
v = new T[initial_capacity];
}
void pushBack(int element)
{
if (counter <= initial_capacity){
v[counter]=element;
counter++;
if (counter == initial_capacity)
initial_capacity += 0.50;
}
}
int size()
{
return counter;
}
friend ostream &operator << (ostream &o, vector t)
{
for (int i=0; i<10; i++)
o<<t.v[i]<<endl;
return o;
}
};
int main()
{
vector <int > v1;
for (int i=0; i<10; i++){
v1.pushBack(i);
}
cout<<v1<<endl;
system ("Pause" );
return 0;
}
Last edited on Mar 5, 2014 at 1:50pm UTC
Mar 5, 2014 at 2:15pm UTC
1 2
default_capacity=1;
v = new T[default_capacity];
Will create an array of size 1
1 2 3
for (int i=0; i<10; i++){
v1.pushBack(i);
}
You are pushing way more than its capacity. Undefined behavior, anything might happen.
initial_capacity += 0.50;
this is equal to
initial_capacity += 0;
Mar 5, 2014 at 2:20pm UTC
So what should I do?
Mar 5, 2014 at 2:24pm UTC
Fix it.
Rethink architecture of your vector. Hint: it will be enough to have just 3 pointer as your class data.
Your function looks like they are unfinished, so finish them.
Topic archived. No new replies allowed.