Does an element insert damage to a vector pointer into a vector?

In a program for simulating logical gates, I switched from using arrays

node N[1000];

to vectors

vector<node> N;

And my program worked fine before using vectors, but now it prints incorrect results, so I tried debugging, and I found out that the error is here:

node* Simulator::FindNode(string h)
{
    int i;
    for(i = 0; i < NNodes; i++)
    {
        if (N[i].getname() == h)
        {
            return &N[i];
        }
    }

    node n ;
    N.push_back(n);
    N[NNodes].setname(h);
    NNodes++;
    return &N[NNodes-1]; //why?because of NNodes++  
}

// ...

node* inp1;
node* inp2;
node* out;
string NodeName;

inp_file >> NodeName;
inp1 = FindNode(NodeName);
s1 = inp1;

inp_file >> NodeName;
inp2 = FindNode(NodeName); //inp1 is destroyed here 

inp_file >> NodeName;
out = FindNode(NodeName); //inp2 and inp1 are destroyed here 

When called FindNodefor the first time, the first inp1 pointer points to the desired location, which is equal &N[0].

When called a FindNodesecond time, the first inp1 pointer points to garbage, and the second inp2 pointer points to the right place &N[1].

When called FindNodefor the third time, both the 1st and 2nd pointers ( inp1, inp2) indicate garbage! And the third pointer points to the right place.

?
, ?

+5
6

.

-, , NNodes . std::vector::size(). , std::vector::back() : return &N.back();.

, , , const-reference: const string& h. , * const, .

:

node n;
N.push_back(n);
N[NNodes].setname(h);

node , const string& . , node , :

node n(h);
N.push_back(n);

:

N.push_back(node(h));

.

-, , vector ; , . , reserve() , . , .

. , , . , , , . Simulator::FindNode a size_t N.size() - 1. node& GetNode(size_t index), return N[index]; ( , ). , , GetNode, node .

- . , deque. , vector. push_back pop_back O (1), - -. (, , deque push_front pop_front O (1) )

, deque push pop . , . deque ( - ), .

, , . . , std::map, , . , .

< > * : const-reference, (, int, double ..), sizeof(void*), .

:

void foo(const std::string& s)
{
    std::string ss(s); // make a copy, use copy
}

:

void foo(std::string s) // make a copy, use copy
{
}

>

+5

, , .

preallocating, . - .

+9

, , .

, , reserve() .

+4

STL, , . STL, . , STL , promises, . , node, - , .

, , node, . , STL, - .

0

, . , deque. .

, , - . . deque deque, , . , .

: !

0

Imagine that you need to write code based on an array so that it can, if necessary, resize the array.

Imagine how you do it.

Imagine what happens with deprecated pointers.

Rewrite the code to use indexes rather than pointers, or to ensure that redistribution does not happen, if necessary.

0
source

All Articles