AlbyTree AlbyTree - 1 year ago 38
C++ Question

How do I add elements to a vector of objects and print them?

Our teacher told us to create a vector of objects and perform operations on it, but I couldn't understand how to properly do that: I tried to make a simple project with minimum data so that I could know what I was doing.

I have this class

class Obj {

private:

int num;

public:

Obj();

void setNum(int nuovo_num);
int getNum();

};


And then this one, with a vector of Obj

class VettObj{

private:

vector<Obj> vett;

public:

VettObj();

void setVett();
void stampaVett();

};


My initial thought was to use an iterator but I was just making a total mess and, with almost useless research, I decided to use a common integer counter.

I found that I shouldn't write anything in the VettObj costructor, as it automatically initialize stuff, so I left it blank.

The method that adds elements is this

void VettObj::setVett(){


Obj temp;
int i;

i = 0;
while(i < 5){


temp.setNum(10);

vett.push_back(temp);

i++;
}

}


And the one that prints elements

void VettObj::stampaVett(){


int i;

i = 0;
while(i < 5){

vett[i].getNum();

i++;
}

}


When I compile, everything goes well, but when I run the program I get nothing on the screen. I don't want to use mostly vector functions(if not necessary) as I saw that a lot of people can do it like this. I would really like to know how to do it with iterators too. Help pls ????

Answer Source

You are not actually printing anything in the stampaVett() method. You could try with:

void VettObj::stampaVett(){

    int i = 0;

    while (i < 5){

        std::cout << vett[i].getNum();

        i++;
    }

}

I'd also suggest using English for method or variable instead of Italian, since SO is an international community.