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
然后是这个,带有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.
我发现我不应该在VettObj costructor中写任何东西,因为它会自动初始化东西,所以我把它留空了。
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 ????
当我编译时,一切顺利,但是当我运行程序时,屏幕上什么都没有。我不想使用大多数矢量函数(如果没有必要),因为我看到很多人都可以这样做。我真的很想知道如何使用迭代器。帮帮忙吧?
1 个解决方案
#1
0
You are not actually printing anything in the stampaVett() method. You could try with:
你实际上并没有在stampaVett()方法中打印任何东西。你可以尝试:
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.
我也建议使用英语作为方法或变量而不是意大利语,因为SO是一个国际社区。
#1
0
You are not actually printing anything in the stampaVett() method. You could try with:
你实际上并没有在stampaVett()方法中打印任何东西。你可以尝试:
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.
我也建议使用英语作为方法或变量而不是意大利语,因为SO是一个国际社区。