Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   STL: Using std::vector to manage an entity (http://www.go4expert.com/forums/stl-using-stdvector-manage-entity-t28418/)

david_BS 20May2012 20:26

STL: Using std::vector to manage an entity
 
Credits: BS, OGC

An entity is represented by a struct, after its creation, a vector of the type of the struct is created to contain some entities.

Code:

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// UTN FRGP TSP
// BS
// mail: david_bs@live.com
// web: Etalking.Com.Ar
// 2012
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <stdio.h>

#include <fstream.h>
#include <string>
#include <vector>

using namespace std;

typedef struct estructura_s{
        int a;
        int b;
        int c;
}estructura_t;

struct ent_info{
        estructura_s* ent;
};

vector<ent_info> vEntidad;

Add and erase entities, also list them
Code:

void AgregarEntidad(struct estructura_s* ent)
{
        ent_info dummy;
        dummy.ent = ent;
        if(vEntidad.size()<64)
                vEntidad.push_back(dummy);
}

void BorrarVectorDeEntidades()
{
        vEntidad.clear();
}

void ListarItemsDeEntidades(){

        for(unsigned int ab=0; ab<vEntidad.size(); ab++){
       
                cout << "La entidad: " << ab << endl;
                cout << "Item 1: " << vEntidad[ab].ent->a << endl;
                cout << "Item 2: " << vEntidad[ab].ent->b << endl;
                cout << "Item 3: " << vEntidad[ab].ent->c << endl;
        }
}

Code:

int main(){

        BorrarVectorDeEntidades();

        struct estructura_s ent1;
        struct estructura_s ent2;
        struct estructura_s ent3;
        ent1.a=111;
        ent1.b=222;
        ent1.c=333;
        ent2.a=444;
        ent2.b=555;
        ent2.c=666;
        ent3.a=777;
        ent3.b=888;
        ent3.c=999;

        AgregarEntidad(&ent1);
        AgregarEntidad(&ent2);
        AgregarEntidad(&ent3);

        ListarItemsDeEntidades();

        cin.get();
        return 0;
}



All times are GMT +5.5. The time now is 12:50.