nested iterator

  • Thread starter Gonzalo Aguirre
  • Start date
G

Gonzalo Aguirre

hi!.
i did this method that should perform as many iterations as Sigma
element has (in the example just two: a, b), for each state (outer
bucle).

vector<_t_> * Mealy::to_deltaMoore() {
vector<_d_>::iterator i;
vector<char>::iterator j;
vector<_d_> vt; // lista de los estados Q útiles
vector<_t_> *v = new vector<_t_>; // vector de transiciones delta
_d_ d0 = {q0, ' '};
_d_ d;
_t_ t;
char q;

//! init state
vt.push_back(d0);

for(i = vt.begin(); i!= vt.end(); i++) // state q
for(j = Sigma.begin(); j!= Sigma.end(); j++){ // input
alphabeth symbol
cout << "q = " << i->a << " con el simbolo: "
<< *j << endl;
d.a = func_delta(i->a, *j); d.b =
func_lambda(i->a, *j);
cout << "delta: " << d.a << " lambda: " << d.b
<< endl;

if(!find(vt, d) && d.a != 0x0)
vt.push_back(d); // <<<---- adding some
elements to outer bucle

t.a = position(vt, *i); t.b = *j; t.c =
position(vt, d);
v->push_back(t);
}
return v;
}

the problem is that i iterator gets mad, and change into the inner
bucle (j iterator) without chaging it! That's the output of the above
method:

q = 1 con el simbolo: a
delta: 2 lambda: #
q = 0 con el simbolo: b <<-- q should be 1!!.. it changes automagically
delta: lambda:
q = con el simbolo: a <<-- q should be 2 (because 2# was add previous
iteration)
delta: lambda:
q = con el simbolo: b <<-- ...
delta: lambda:
....

is that a known bug.. or i should continue looking for the bug into my
method?

thanks in advance
 
V

Victor Bazarov

Gonzalo said:
[...]
for(i = vt.begin(); i!= vt.end(); i++) // state q
> [...]
if(!find(vt, d) && d.a != 0x0)
vt.push_back(d); // <<<---- adding some
elements to outer bucle
[...]
the problem is that i iterator gets mad, and change into the inner
bucle (j iterator) without chaging it!

When you 'push_back' into 'vt', it is allowed to _reallocate_. That makes
any iterators (and pointers, and references) to any elements of the vector
*invalid*. Using an invalid iterator causes undefined behaviour. So, any
time you try to dereference or even increment an invalid iterator, the
program is allowed to do as it pleases and not as you think.

Do not use iterator. Use an index.
> [..]

is that a known bug.. or i should continue looking for the bug into my
method?

It's not a bug. At least not in the behaviour of 'std::vector'. It is
a bug in your understanding of what to expect.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,219
Latest member
KristieKoh

Latest Threads

Top