C++ 结构/类中向量的初始化和打印输出

C++ 结构/类中向量的初始化和打印输出,c++,vector,constructor,iterator,C++,Vector,Constructor,Iterator,我实际上是在尝试初始化struct/class的构造函数中的向量 我想出了这些,下面的内容编译没有错误,但不打印出向量中的内容。我想知道为什么,我会非常感激你的帮助 struct MyInt { friend ostream &operator<<(ostream &printout, const MyInt &Qn) { printout<< Qn.value << endl; return printout; }

我实际上是在尝试初始化struct/class的构造函数中的向量

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

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;
}
struct MyInt
{
friend-ostream&operatorvalues.end();++VITER)
{

cout未定义的行为。您的指针无效。因为这里根本不需要指针,只需使用值即可:

MyStuff mystuff1, mystuff2;

// ...
mystuff1.push_back(...); // et cetera

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

有趣的是,这没有崩溃。可能编译器将代码视为无法访问,并删除了所有内容?@usr:行为未定义。当月球在ri时,它可能会崩溃正确的位置。当然,但是为什么实现是这样的呢?很有趣。