Error: "there is no match for the + operator" for the list iterator

In the code below, I get an error in the header for the string

while((*(It2 + code)).exists){ 


 void locatetohashtable(std::list<Element> elist, int *m,std::list<Element>& table, std::list<std::string>& keylist ) { std::list<Element>::iterator It2=table.begin(); int i=0; int k=0; std::list<Element>::iterator It; for(It = elist.begin(); It != elist.end(); ++It) { int code=hash_func(stringIntValue((*It).name),*m,i); while((*(It2 + code)).exists){ i++; } table.insert(*(It2+i), (*It)); keylist.insert(keylist.begin(),(*It).name); k++; } } 

I do not get the same error for ++It

What is the problem?

+6
source share
4 answers

An iterator for std::list is bidirectional, so it does not support +(int) . The only supported move operations are ++ and -- .

+11
source

This is because the std::list iterators are bidirectional iterators , so they do not support the add operation you are trying to perform. In practice, this is due to the fact that it cannot be implemented as an efficient operation, since lists do not provide random access, so you will need to perform a one-time increment from the initial iterator to the target one. The constructive solution is not to provide an operation that will be ineffective.

You can use std::advance or std::next to avoid writing your own increment loops, but under the hood it will gradually increase.

+9
source

std::list iterators have only bi-directional, not random access, so you cannot use the + operator to advance them. Use std::next (C ++ 11) or std::advance .

+4
source

This is a "Concept" question.

A list can be moved forward and backward efficiently, so its iterators model the concept of a bidirectional iterator.

You can use std::advance to move the iterator at once by several positions, however this will not be effective.

Or you can change the use of vector or deque instead of a list. Because they are Random Access containers, their iterators support addition and subtraction efficiently.

+2
source

Source: https://habr.com/ru/post/915561/


All Articles