简体   繁体   中英

Vector Initialisation in C++

I am using Vectors in my code.

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<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++.

For your reference the complete Method function is here :

http://pastebin.com/2dUFEui5

Your Node class has a pointer member of type CombinedFragment* called cfrag . This creates dangling references if you don't defined your own copy ctor and assignment operators. Further, a proper dtor is required to prevent leaks if Node is responsible for allocating/deallocating cfrag . If you don't want to deep-copy CombinedFragment you can use a shared_ptr .

Also, the default ctor for Node probably doesn't even need to be there (it leaves cfrag to an uninitialized state).

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. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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