简体   繁体   English

C ++中的向量初始化

[英]Vector Initialisation in C++

I am using Vectors in my code. 我在我的代码中使用Vectors。

The line that is causing the error is as follows : 导致错误的行如下:

vector<Node> alt_seq ;
alt_seq = vector<Node>(1000);
for(int j=0; j<alt_cf.getNoOfNodes(i); j++)
{
    Node temp_node = *alt_itr;
    alt_itr++;
    alt_seq.push_back(temp_node);
    }

The line : 这条线:

 alt_seq.push_back(temp_node);

causes a runtime error. 导致运行时错误。 However if I initialise the Vector with some initial size as follows: 但是,如果我使用一些初始大小初始化Vector,如下所示:

vector<Node> alt_seq(1000) ;

In this case the code works fine. 在这种情况下,代码工作正常。 However I do not want to give an initial size as the number of objects in the vector will be variable at runtime. 但是我不想给出初始大小,因为向量中的对象数量在运行时是可变的。 Please help me. 请帮我。 I am new with C++. 我是C ++的新手。

For your reference the complete Method function is here : 供您参考,完整的Method函数在这里:

http://pastebin.com/2dUFEui5 http://pastebin.com/2dUFEui5

Your Node class has a pointer member of type CombinedFragment* called cfrag . 您的Node类有一个CombinedFragment*类型的指针成员,称为cfrag This creates dangling references if you don't defined your own copy ctor and assignment operators. 如果您没有定义自己的复制ctor和赋值运算符,则会创建悬空引用。 Further, a proper dtor is required to prevent leaks if Node is responsible for allocating/deallocating cfrag . 此外,如果Node负责分配/解除分配cfrag ,则需要适当的dtor来防止泄漏。 If you don't want to deep-copy CombinedFragment you can use a shared_ptr . 如果您不想深度复制CombinedFragment ,可以使用shared_ptr

Also, the default ctor for Node probably doesn't even need to be there (it leaves cfrag to an uninitialized state). 此外, Node的默认ctor可能甚至不需要在那里(它将cfrag为未初始化状态)。

I can see one problem; 我可以看到一个问题; when you declare 1000 vector objects and then do a push_back you're adding to the end of the vector, ie the objects that you're trying to add are at 1001, 1002.... etc. If declaring 1000 vector objects doesn't give you a runtime error, I would first see what's the default definition (since the first 1000 node objects have default values), since that's not error out and compare against the actual data I'm trying to load. 当你声明1000个vector对象,然后执行push_back你将添加到矢量的末尾,即你想要添加的对象是1001,1002 ......等等。如果声明1000个vector对象没有t给你一个运行时错误,我首先会看到默认定义是什么(因为前1000个节点对象有默认值),因为这不是错误输出并与我试图加载的实际数据进行比较。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM