Zohaib
Zohaib

Reputation: 363

An error faced using vector iterator

Well in my program i have made a class of name 'Transition'. When i made a vector of Transition type named delta_. And when later in one of my functions implementation of the class where i have declared delta_, i tried to use iterator with the syntax given below:

vector<Transition>::iterator it;
it=this->delta_.begin();

i got these two errors:

In constructor `__gnu_cxx::__normal_iterator<_Iterator, Container>::_normal_iterator(const __gnu_cxx::__normal_iterator<_Iter, _Container>&) [with _Iter = const Fa::Transition*, _Iterator = Fa::Transition*, _Container = std::vector >]':

invalid conversion from const Fa::Transition* const' toFa::Transition*'

Now i really have no idea where the mistake is. Can anybody please help!!

Upvotes: 2

Views: 152

Answers (2)

Dmitriy Kachko
Dmitriy Kachko

Reputation: 2914

Let me guess, are you doing it=this->delta_.begin(); in a const method of the class, and delta_ is a member of the class?

A constness of the method guarantees that members of the class will not changed. But the variable it has non-const type iterator, and that gives possibility to change the member delta_ which makes the protection corrupt.

The std::vector has two overloaded methods begin()

iterator begin ();
const_iterator begin () const;

If you use begin() in a method which is const, compiler calls second one.

So you need to refuse from constness of the method, or use const_iterator.

Another possible way, which I do not recommend because of blurring constness of the object, is to put your vector on a heap and operate with a pointer to it.

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92211

Either this or delta_ seems to be const, causing begin() to return a const_iterator.

Upvotes: 1

Related Questions