初始化结构/类中的向量并打印出来

Initialization of vectors in a struct/class and print out

本文关键字:打印 向量 结构 初始化      更新时间:2023-10-16

我实际上正在尝试初始化结构/类构造函数中的向量。

我想出了这些,下面的内容编译没有错误,但是没有打印出向量中的内容。我想知道为什么,帮助将不胜感激!

struct MyInt
{
friend ostream &operator<<(ostream &printout, const MyInt &Qn)
{
    printout<< Qn.value << endl;
    return printout;
}
     int value;
     MyInt (int value) : value (value) {}
};
struct MyStuff
{
    std::vector<MyInt> values;
MyStuff () : values ()
    {
        values.reserve (10); // Reserve memory not to allocate it 10 times...
    }
};
int main()
{
MyStuff *mystuff1;
MyStuff *mystuff2;
for (int i = 0; i < 10; ++i)
{
        mystuff1->values.push_back (MyInt (i));
}
for (int x = 0; x < 5; ++x)
{
        mystuff2->values.push_back (MyInt (x));
}
vector<MyInt>::iterator VITER;
for (VITER =mystuff1->values.begin(); VITER!=mystuff1->values.end(); ++VITER)
{
    cout<< *VITER;
}
return 0;
}

未定义的行为。您的指针无效。由于您在这里根本不需要指针,因此只需使用值:

MyStuff mystuff1, mystuff2;
// ...
mystuff1.push_back(...); // et cetera

此外,如果您不保留,它仍然不会分配 10 次。 vector实现足够智能,不会每次增加 1 个容量。