STL容器默认初始化
你好 我有以下struct
struct node {
std::string word
std::vector<struct node *> child;
}
当我创建新节点时,我无法初始化子向量
。 我本质上想要的是使用 operator[]
检查任何元素是否有有效值。 我想做以下事情
if ( nodeptr->child[5] ) {
}
,但代码在 if 循环处崩溃。
还有其他方法可以处理这个问题吗?
Hello
I have following struct
struct node {
std::string word
std::vector<struct node *> child;
}
When I create the new node, I have no way to initialize child vector
.
What I essentially want is to check any element using operator[]
is there is valid value.
I want to do following
if ( nodeptr->child[5] ) {
}
But Code crashes at if loop.
Is there other way to handle this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,您必须为您的结构提供一个构造函数。
这将使用 10 个 NULL 指针初始化向量。然后,您可以检查索引是否为 NULL(意味着它不包含数据)或不是(它包含数据)。
In this case you would have to provide a constructor for you struct.
This will initialize the vector with 10
NULL
-pointers. You can then check if an index isNULL
(meaning it does not contain data), or not (it does contain data).问题不清楚您的实际问题是什么,即您是否需要向量在构造后具有给定的大小,或者您是否只想检查是否插入了第五个元素。
在第一种情况下,向量的大小是节点类的不变量,您应该在构造过程中强制执行不变量。向
node
添加构造函数(正如其他人之前建议的那样):另一方面,如果向量的大小不是不变式,并且您想要检查第五个元素是否已插入以及是否它不为空,然后更改 if 条件:
该条件将首先验证向量是否已足够增长(要访问位置 5 处的元素,大小必须为 6 或以上),然后验证位置 5 处的元素是否不为空。无效的。注意
&&
会短路,所以如果第一个条件不满足,则不测试第二个条件。The question is not clear on what your actual problem is, that is whether you need the vector go have a given size after construction or whether you just want to check if a fifth element was inserted.
In the first case, the size of the vector is an invariant of the node class, you should enforce the invariant during the construction. Add a constructor to
node
(as others have suggested before):If, on the other hand, the size of the vector is not an invariant, and you want to check whether the fifth element was inserted and whether it is non null, then change the if condition:
That condition will verify first that the vector has grown enough (to access the element at position 5, the size must be 6 or above), and then whether the element at position 5 is not null. Note that
&&
will short circuit, so if the first condition is not met, the second condition is not tested.Vector 有一个构造函数,它接受计数和值。
用那个。为节点定义构造函数:
node::node()
:孩子(10,空)
{
}
Vector has a constructor which takes a count and a value.
Use that. Define a constructor for node:
node::node()
: child( 10, NULL )
{
}