Patrick Perini
Patrick Perini

Reputation: 22633

const_iterator to iterator C++ Error

I'm trying to iterator through a map object using the following chunk of code:

for(map<int, vector>::iterator table_iter = table.being(); table_iter != table.end(); table_iter++)
{
    ...
}

And I keep getting errors telling me:

conversion from const_iterator to non-scalar type iterator requested

And I can't seem to determine why the iterator would be const vs. not-const, or how to deal with this.

Upvotes: 6

Views: 9492

Answers (4)

Xeo
Xeo

Reputation: 131799

Sounds like table is a const object or reference, in which case begin returns a const_iterator. Change your for-loop to this:

// typedefs make for an easier live, note const_iterator
typedef map<int, vector>::const_iterator iter_type;
for(iter_type table_iter = table.begin(); table_iter != table.end(); table_iter++)
{
    ...
}

Upvotes: 2

Despairy
Despairy

Reputation: 13

Well, your question was partially answered.

"And I can't seem to determine why the iterator would be const vs. not-const, or how to deal with this." As others answered, if your table is defined as a constant you need to define a const iterator. What was missing is that if the function is defined as const the iterator should be const as well.

I figured a const function was your issue rather than a const table.

Upvotes: 1

danca
danca

Reputation: 509

Use map<int, vector>::const_iterator instead which is returned by map::begin.

Upvotes: 9

smparkes
smparkes

Reputation: 14063

I'm guessing table is a const&.

Upvotes: 0

Related Questions