Skip to content

Instantly share code, notes, and snippets.

@matthiasdebernardini
Created October 22, 2017 12:33
Show Gist options
  • Save matthiasdebernardini/e6e3cdf58e691902f7dcd28854f02515 to your computer and use it in GitHub Desktop.
Save matthiasdebernardini/e6e3cdf58e691902f7dcd28854f02515 to your computer and use it in GitHub Desktop.
struct inside of custom vector
#include <iostream>
using namespace std;
struct Person
{
string name;
string room;
};
class myvector
{
private:
int vsize;
int maxsize;
Person* array;
void alloc_new();
public:
myvector();
myvector(Person);
myvector(const myvector&); //copy constructor
~myvector();
void push_back(Person);
int size();
int operator [] (Person);
int at(int i);
};
myvector::myvector()
{
maxsize = 20;
array = new Person[maxsize];
vsize = 0;
}
myvector::myvector(int i)
{
maxsize = i;
array = new Person[maxsize];
vsize = 0;
}
myvector::myvector(const myvector& v)
{
maxsize = v.maxsize;
vsize = v.vsize;
array = new Person(maxsize);
for(int i = 0; i < v.vsize ; i++)
{
array[i] = v.array[i];
}
}
myvector::~myvector()
{
delete[] array;
}
void myvector::push_back(Person i)
{
if(vsize + 1 > maxsize)
{
alloc_new();
}
array[vsize] = i;
vsize++;
}
int myvector::operator[] (int i)
{
return array[i];
}
int myvector::at(int i)
{
if(i < vsize)
{
return array[i];
}
}
int myvector::size()
{
return vsize;
}
void myvector::alloc_new()
{
maxsize = vsize*2;
Person *tmp = new Person[maxsize];
for(int i = 0; i < vsize; i++)
{
tmp[i] = array[i];
}
delete[] array;
array = tmp;
}
int main()
{
string name;
string room;
myvector vec;
Person tmp;
while(1)
{
cin >> tmp;
//if (tmp == -1)
{
break;
}
vec.push_back(tmp);
}
cout << "you have entered" << vec.size() << "elements. These are: \n";
for(int i = 0; i < vec.size(); i++)
{
//cout << vec[i] << " ";
}
cout << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment