Answer the question
In order to leave comments, you need to log in
How to dynamically increase the size of an array?
I'm trying to create an analogue of an associative array, through 2 classes.
One class where the data itself is described:
data.h
#pragma once
#include "myString.h"
enum gender{MALE,FEMALE};
class data
{
MyString surname, name, position;
unsigned char age;
int salary;
gender myGen;
public:
/*data();*/
data(MyString nameIn = MyString("Anonymous"), MyString positionIn = MyString("No position"), unsigned char ageIn = 18, int salaryIn = 8000, gender genIn = MALE, MyString surnameIn = MyString("Anonymous"));
friend ostream& operator<<(ostream& os, const data& inputData);
data& operator=(const data& inputData);
~data();
friend class BD;
};
#include "data.h"
using namespace std;
data::data(MyString nameIn, MyString positionIn, unsigned char ageIn, int salaryIn, gender genIn, MyString surnameIn)
{
myGen = genIn;
name = nameIn;
surname = surnameIn;
age = ageIn;
salary = salaryIn;
position = positionIn;
}
data::~data()
{
}
ostream& operator<<(ostream& os, const data& inputData){
os << "Surname: " << inputData.surname << "\nName: " << inputData.name << "\nAge: " << static_cast<int>(inputData.age) << "\nSalary: " << inputData.salary << "\nPosition: " << inputData.position << endl;
return os;
}
data& data::operator=(const data& inputData){
this->age = inputData.age;
this->myGen = inputData.myGen;
this->name = inputData.name;
this->position = inputData.position;
this->salary = inputData.salary;
return *this;
}
#pragma once
#include "data.h"
class BD
{
data* man;
int cap;
public:
BD();
data& operator[](const MyString& family);
friend ostream& operator<<(ostream& os, const BD& inputBD);
~BD();
};
#include "BD.h"
BD::BD()
{
man = nullptr;
//man = new data[1];
cap = 0;
}
BD::~BD()
{
delete[] man;
}
data& BD::operator[](const MyString& family){
for (int i = 0; i < cap; i++){
if (this->man[i].surname == family){
return this->man[i];
}
}
cap++;
data* tmp = new data[cap];
if (cap>1)
{
memcpy(tmp, this->man, sizeof(data)*(cap-1));
delete[] this->man;
}
this->man = tmp;
this->man[cap - 1].surname=family;
return this->man[cap - 1];
}
ostream& operator<<(ostream& os, const BD& inputBD){
for (int i = 0; i < inputBD.cap; i++)
{
os << "Person #" << inputBD.cap << "\n" << inputBD.man << std::endl;
}
return os;
}
memcpy(tmp, this->man, sizeof(data)*(cap-1));
delete[] this->man;
Answer the question
In order to leave comments, you need to log in
remember the pointer to the current start
and use realloc to allocate memory and point it to our pointer
I'm trying to create an analogue of an associative array, through 2 classes.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question