tailieunhanh - C++ Programming for Games Module II phần 3

Tham khảo tài liệu 'c++ programming for games module ii phần 3', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | Traversing For general purposes the C containers work with iterators. Iterators are objects that refer to a particular element in a container. Iterators provide operators for navigating the container and for accessing the actual element to which is being referred. Iterators overload pointer related operations for this functionality. In this way pointers can be thought of as iterators for raw C arrays. For example the data to which an iterator refers is accessed with the dereference operator . We can move the iterator to the next and previous element using pointer arithmetic operators such as and --. We can use these operators because they have been overloaded for the iterator. Note however that although these operators behave similarly the underlying implementation will be different for different containers. For example moving up and down the nodes of a linked list is different than moving up and down the elements of an array. However by using iterators and the same symbols to move up and down a very beautiful generic framework is constructed. Because every container has the same iterators using the same symbols that know how to iterate over the container a client of the code does not necessarily need to know the type of container. It can work generally with the iterators and the iterators will know how to iterate over the respective container in a polymorphic fashion. Note The obvious implementation of an iterator is as a pointer. However this need not be the case and you are best not thinking that it necessarily is. The implementations of iterators vary depending on the container they are used for. Getting back to std list we can iterate over all the elements in a list as follows list int iterator iter 0 for iter iter iter cout iter cout endl First we declare a list iterator called iter. We then initialize this iterator with which returns an iterator to the first node in the list. Then we loop as long as iter .