Matt Austern: Defining Iterators and const itrators

zhaozj2021-02-16  52

The Standard Librarian: Defining Iterators and Const Iterators

Matt austern

Writing an itrator isn't Hard, And It's a Natural Way to Extend The C Standard Library. But if you want to do it right, There Are A few Wrinkles you ught to know about.

The Standard C library is extensible by design:. Standard algorithms such as reverse and partition operate on the predefined containers like vector and list, and they can also operate on any user-defined data structure that supplies the appropriate iterators Using the library effectively involves extending IT.

By now, iterators are familiar to most C programmers Iterators abstract the most basic properties of pointers:. A forward iterator points to some object in a sequence, and it can be incremented so that it points to the next element in the sequence (Stronger. Iterator Categories, Bidirectional Iterators and Random Access Iterators, Provide Additional Means of Traversing Sequences. Weaker Iterator Categories Are INAPPRIATE for MOST DATA STRUCTURES.

Every iterator has a category type (std :: forward_iterator_tag in the case of a forward iterator), a value type (the type of the object it points to), a difference type (an integer type that represents the distance between two elements of a sequence), and a pointer and reference type (pointer and reference to the iterator's value type) Those types are accessed through the std :: iterator_traits class;. the easiest way for you to provide them, when defining your own iterator class, is to Provide The as nested typedefs: iterator_category, value_type, difference_type, pointer, and reason.

A forward iterator is any type that satisfies the requirements in §24.1.3 of the C Standard; that section of the Standard tells you what member functions and overloaded operators have to be defined Once you've figured out what information an iterator must keep. TRACK OF SO THAT IT CAN POINT TO An Element And So That Can Find The Next Element, Defining a Forward Itel IS Just A Matter of Filling In Those Functions' Definitions.matched Pairs of iTerators

One complication is that it usually is not enough to define an iterator class. You probably need to define two iterator classes, one that permits modification of the object it points to (* i returns a reference to the object) and one that does not (* i returns a const reference) The library's predefined container classes do this:. the std :: list class, for example, has a nested type iterator and a different nested type const_iterator; the latter can be used to traverse a const std: : List. The value Types of list :: Iterator and list :: const_iterator is Both T, But The Reference Type and Pointer Type Differ: for list :: item They area T & and T * Respectively While for List :: Const_Iterator They Are Const T & and Const T *. You CAN Convert A List :: Iterator To A List :: Const_Iterator, But (for Obvious Reasons Of Const Correctness) Not The Other Way Around.

Matched pairs of iterators are just as common in user-defined types as they are in predefined standard library types Suppose, for example, that you're defining a simple singly linked list class You might start with something like this..:

Template

Struct slist_node {

T Val;

SLIST_NODE * NEXT;

Slist_node

(Const T & T, SLIST_NODE * P)

: VAL (t), Next (p) {}

}

Template struct slist {

SLIST_NODE * HEAD;

...

}

An Iterator Class for SLIST CAN Be Equally Simple:

Template

Struct slist_iterator {

Typedef std :: forward_iterator_tag

Iterator_category;

Typedef t value_type;

Typedef std :: ptrdiff_t

Difference_type;

TYPEDEF T & REFERENCE;

Typedef t * pointer;

SLIST_ITERATOR (slist_node * x = 0)

: p (x) {}

SLIST_ITERATOR

(Const Slist_Iiterator & i)

: p (i.p) {}

Reference Operator * () const

{RETURN P-> Val;}

Pointer Operator -> () const

{RETURN & (P-> VAL);

SLIST_ITERATOR & OPERATOR () {

P = P-> next;

Return * this;

}

SLIST_ITERATOR OPERATOR (int) {

SLIST_ITERATOR TMP (* THIS);

* THIS;

Return TMP;

}

SLIST_NODE * P;

}

How should we define the matching const iterator We could just define a separate slist_const_iterator class, but code duplication is wasteful and error-prone The changes to turn slist_iterator into slist_const_iterator are tiny?.:

• DECLARE P To Bey Type const slist_node * instead of slist_node *.

• DECLARE POINTER AND REFERENCE TO BE Const T * and const T & INSTEAD OF T * AND T & INSTER

• Define a communication constructor what takes an argument of type slist_iterator.

None of these are obstacles to defining a single class that can take the place of both slist_iterator and slist_const_iterator. We define an iterator class additional template parameters, and those parameters determine whether or not it's a const iterator with. We give the class a constructor that takes the non-const version as an argument;. in one case it will be a copy constructor, in the other case a converting constructor The other two differences just involve changing one type to another, so it's easy to encapsulate those differences as template parameters .Finally: what should those extra template parameters look like in my book [1], I proposed explicitly passing the pointer and reference types as template parameters That method is adequate, but it results in somewhat cumbersome type names; there's a cleaner solution?. . We can provide Just A Single Extra Template Parameter, a Boolean Flag That Determines WHETER OR NOT We're Defining a const itrator, and then use a little bit of Machinery, a '' compile-time?: operator '' That Selects One Type OR Another Based On That Flag [2]. This is Shown in Listing 1.

Equality Comparisons

We Haven't Yet Defined An Equality Operator. There's Still One Snag, And You Can Even SNAGER OF THE Standard Library's Predefined Ite CoMPiling this Program:

#include

Int main () {

Std :: deve D;

Std :: deve :: const_iterator i = d.begin ();

While (d.end ()! = i)

D;

}

. The program does not do anything, but that's not the point The point is that, with many existing library implementations, it will not even compile Are those implementations buggy Not necessarily;.? I is of type deque :: const_iterator and d.begin returns a deque :: iterator, and the C Standard is not completely clear whether or not an equality comparison between the two is guaranteed to work [3]. Even if the Standard does not explicitly require this, however, it's certainly more friendly if you support it in your own iterator classes.You might wonder how this could possibly be a problem. After all, have not we already said that a container's iterator type can always be converted to its const Iterator Type? if d.begin () Can Be Converted Into a Deque <> :: const_iterator, the why can't you compare them?

The problem is that there are a number of different ways to define equality operators for an iterator; if they're defined in either of the two most obvious ways, comparisons between a container's iterator and const iterator types will not work.

First, suppose operator == is defined as a member function. That's not quite good enough. If i is a debquie <> :: const_iterator, and j is a deque <> :: item, then i == j Will Work Butk == i won't. it's simple enough to see the reason for the assephametry: Member functions are inherently asymmetric. an expression Like Af (b) (or, in this case, j. ga == (i)) Invokes a specific .

That's obvious enough, so your next thought might be to define operator == as a non-member function Unfortunately, doing that in the obvious way is even worse A simple toy program illustrates the problem:.! Template struct A { }

Template struct b {

B () {}

B (a ) {}

}

Template

Void F (B , B ) {}

Int main () {

A a;

B b (a); // ok, a is

// converTible to B

f (a, b); // Doesn't Work

}

IT's Not Good Enough for a to Be Convertible to B. If F Wern't A Template, There Would Be No Problem: The Compiler Would Apply The User-Defined Conversion from a to b . Since f Depends ON a template parameter T, however, another step has to come first: the compiler has to deduce a value for T that makes the function call match f's argument list In this case there can be no match:. f's declaration says that its arguments are of The Same Type, But We're Trying To Call It With Two Different Types. Template Argument Deduction Requires An Exact Match [4]; user-defined conversions aren't considered.

We can't Declare Operator == as a member function, and we can't declare it as a non-mer function template. It way to declare a whole fasmily of non-template functions, one For EVERY POSIBLE INSTANTIATION OF THE ITERATOR CLASS. THIS An ODD Requirement, Since A Family of Parameterized functions is Just What Templates Are's Actually Possible.

It's possible because of an obscure loophole in the way friend declarations of class templates work [5]. You can explicitly declare a friend function to be a template. If you do not, however, and if it does not match a previously declared Function Template, THE Compiler Assumes It to be an order. for example: template void g (t);

Template struct x {

// f Is a function Template

Friend Void F (T);

// g is a function template

Friend void :: g (t);

// h is a non-template function

Friend void h (t);

}

Usually this is just a nuisance: normally you want the compiler to treat something like h as the declaration of a function template, so you have to remember to declare it in such a way that it does get treated as one Occasionally, however, this. quirk is genuinely useful If you define a function as part of a friend declaration, and if you declare it as a non-template friend, you'll get a family of non-template functions -. just what we needed for an iterator's equality operator .

Template struct x {

Friend void f (t) {} // f is a non-template function

}

A Complete Definition of Slist_IpectRATOR, INCLUDING THE Equality Operator, IS Shown In Listing 2.

Summary

When you write a container, or something like a container, it's usually not enough to define a single iterator class. You need to define a matched pair of iterator and const iterator classes. Defining such a matched pair presents some implementation issues that do not Arise if you're defining a single iterator class thing stands on its oow.

The two classes in the iterator / const iterator pair must have the same iterator category, difference type, and value type; the iterator class must be convertible to the const iterator class, but not vice versa You can define the iterator and const iterator types. as a single class, by adding an additional template parameter and using the choose template, or something like it, to define the iterator's nested types appropriately. If you're using one of the predefined container classes (string, vector, list, deque, Set, MAP, MULTISET, MULTIMAP, You Should Avoid Comparing One of Its Iterators to One of Its Const Iterators. If D Is A Deque (As Opposed To a const deque &), you shouth't writestdd :: Deque : : const_iterator i = d.begin ();

While (i! = d.end ())

...

You Should WRITE

Std :: Deque :: item i = d.begin ();

While (i! = d.end ())

...

instead. The C Standard does not explicitly say that the first form should work, and, indeed, it does not work on all implementations. Your programs will be more portable if you avoid it. When you're defining your own matched pair of Iterator and const iterator classes, you can Easily make Sure That Comparisons Between The Two Will Work Properly; Just Make Sure To Define The Comparison Operators As Non-Template Friend Functions. O

转载请注明原文地址:https://www.9cbs.com/read-23588.html

New Post(0)