我需要显示容器类型为struct *的向量元素。向量的元素指向结构。以下是结构的以下代码:
struct cheader //header of a linked list
{
int id;
int totald;
class c* next = NULL;
cheader(int x, int y)
{
id = x;
totald = y;
}
};
typedef struct cheader ch;
vector<ch*>present;
存在的向量包含指向此结构的指针。在其他一些功能中添加了指向此结构的指针。 现在,我想编写一个函数来显示向量结构的内容。 请建议如何做到这一点。
答案 0 :(得分:0)
你可以这样做
for (int i = 0; i < present.size(); ++i)
cout << present[i]->id << " ";
或在C ++ 11中
for (auto p : present)
cout << p->id << " ";
我希望它有所帮助
答案 1 :(得分:0)
首先,您必须传递向量中的所有元素。你必须使用迭代器来实现它:
for (vector<ch *>::iterator yourIt = present.begin(); yourIt != present.end(); ++it)
然后,在你的内心,你只需做你想做的事。迭代器是指向向量元素的简单指针。在这种情况下,你的迭代器将是一个'ch **'。
获取他的内容,你只需要取消引用你的指针,并使用你想要的变量。例如:
for (vector<ch *>::iterator yourIt = present.begin(); yourIt != present.end(); ++it)
{
cout << "The id : " << (*it)->id << " And the Totald : " << (*it)->totald << endl;
}
乍一看可能看起来很奇怪,但C ++容器(如矢量)非常有用!他们有很多很棒的会员功能!我建议您查看此页面:http://www.cplusplus.com/reference/stl/;)
而且,我只想补充一点,例如,使用向量,你有一个'[]'运算符。这意味着你也可以这样做:
for (int i = 0; i < present.size(); ++i)
{
cout << (present[i])->id << endl; /* For example ;) */
}
希望这有助于你;)