jeudi 1 novembre 2018

Initialize and declare dynamically multiple variables of random entities in a loop in C++

This is my code:

#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <vector>
#define ENTITY(A) entity##A
#define ALM(A) alm##A

struct TEntity{
private:
    int sumx;
    int sumy;
    const char * rep;
    int m_ix;
    int m_iy;
public:
    TEntity(int x, int y, int sum_x, int sum_y, const char * txt);
};

TEntity::TEntity(int x, int y, int sum_x, int sum_y, const char * txt) {
    m_ix = x;
    m_iy = y;
    sumx = sum_x;
    sumy = sum_y;
    rep = txt;
}

class IAlmacenable {
private:
    void * element;
public:
    IAlmacenable(void * e);
    IAlmacenable();
    void * getValue();
};

IAlmacenable::IAlmacenable(void *e) {
    element = e;
}

IAlmacenable::IAlmacenable() {
    element = nullptr;
}

void * IAlmacenable::getValue() {
    return element;
}

class TList {
private:
     std::vector<IAlmacenable*> elementos;
     int position;
public:
    TList();

    int Size();

    int Push(IAlmacenable* psz);
};

TList::TList() {
    elementos = std::vector<IAlmacenable*>();
    position = 0;
}

int TList::Size() {
    return elementos.size();
}

int TList::Push(IAlmacenable* psz) {
    int res = 0;
    if (elementos.size() >= elementos.max_size()) {
        res = -1;
    }
    else {
        elementos.push_back(psz);
    }
    return res;
}

int main(){
    srand(time(NULL));

    TList *list = new TList();
    //we can put entities in the list and the rest will be filled up to 5
    int size = list->Size();
    for(int i = size; i<5;i++){
        const char c[] = {(rand() % 2 ? 65 + rand() % 25 : 97 + rand() % 25), '\0'};
        TEntity ENTITY(i)(rand() % 10, rand() % 10, rand() % 5, rand() % 5, c);
        IAlmacenable ALM(i)(&ENTITY(i));
        list->Push(&ALM(i));
        size++;
    }
    //do things like printing their value...
    delete list;
    return 0;
}

I need to create a new variable everytime it run the "TEntity ENTITY(i)" line, but it create the same variable all the time and I need to get different random number for every parameter when I initialize the TEntity. The c variable create a const char * random variable between a-z, A-Z , I don't put the print code because it is unnecessary, so what can I do? Is there any way to dynamically create variables of entities whose values ​​are random?

Aucun commentaire:

Enregistrer un commentaire