初始化结构/类中的向量并打印出来
Initialization of vectors in a struct/class and print out
我实际上正在尝试初始化结构/类构造函数中的向量。
我想出了这些,下面的内容编译没有错误,但是没有打印出向量中的内容。我想知道为什么,帮助将不胜感激!
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 个容量。
相关文章:
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 如何在 c++ 中打印存档中的对象向量
- 如何在C++中打印对象向量的内容
- 从函数返回向量以打印内容
- 为什么 c++ 不能打印向量 B[0]?
- 打印出对象向量中的每个元素C++
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员
- 如何在C 中打印字符串向量的向量
- 如何打印出唯一指针对象向量中的值(基于范围的循环)?C++
- 无法打印字符向量C++向量
- Windbg C 如何打印向量内容
- circle类和班级成员的打印向量发行
- 如何在递归函数中打印向量
- 重载<<运算符打印向量的前n个值(不是整个向量)
- 打印向量 - 空输出
- 打印向量元素错误消息
- 在C 中打印向量阵列
- 如何填充和打印向量集的向量
- 我如何访问和打印向量的向量中的单个元素