How to get data from STL const_iterator?

I have something that works as follows:

T baseline; list<T>::const_iterator it = mylist.begin(); while (it != mylist.end()) { if (it == baseline) /* <----- This is what I want to make happen */ // do stuff } 

My problem is that I have no idea how to extract data from an iterator. I feel that this is a stupid thing to be confused, but I have no idea how to do this.

EDIT: Fixed begin.end ()

+4
source share
6 answers

Iterators have an interface that "looks" like a pointer (but they are not necessarily pointers, so don't use this metaphor too far).

An iterator provides a link to a single piece of data in a container. You want to access the contents of the container at the position indicated by the iterator. You can access content in the it position with *it . Similarly, you can call methods on the content in the it position (if the content is an object) using it->method() .

This really does not apply to your question, but to spread the error is to be on the lookout (even from time to time I do this time): if the content in the it position is a pointer to an object, to call the methods of the object, the syntax (*it)->method() , since there are two levels of indirection.

+9
source

The syntax for using an iterator is basically the same as with a pointer. To get the value that the iterator points to, you can use dereferencing with * :

  if (*it == baseline) ... 

If the list is a list of objects, you can also access the methods and properties of objects using -> :

  if (it->someValue == baseline) ... 
+3
source

Using:

 if (*it == baseline) 
+2
source

Use * to access the item specified by the iterator. When you compare, I think you should use if (* it == baseline)

+1
source

The std iterators overload the * () operator, so you can access the reference location just as if it were a pointer.

 T const& a = *it; 
+1
source

from what I know, std iterators are not pointers, but they are a thin wrapper around the actual pointers to the main individual data elements.

you can use something=*it to access the element specified by the iterator.

The source code * it == is the correct code for this behavior.

Also, if you are dealing with collections from the STL, you can use functions such as find_if http://www.cplusplus.com/reference/algorithm/find_if/

0
source

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


All Articles