first commit

This commit is contained in:
Jose Caban
2025-06-07 11:34:38 -04:00
commit 0eb2d7c07d
4708 changed files with 1500614 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Welcome</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>1.1 Welcome</H2>
<P>Congratulations on choosing the Apache C++ Standard Library, developed and donated to the Apache Software Foundation by <a href="http://www.roguewave.com">Rogue Wave Software</a>. You can use this product with confidence: it is based on the final standard for the C++ language and library ratified in 1998 by the American National Standards Institute (ANSI) and the International Standards Organization (ISO).</P>
<A NAME="idx1"><!></A>
<P>Since its development by Dr. Bjarne Stroustrup in the 1980s, the C++ language has been widely used by professional programmers for the world's big, complex applications in telecommunications, finance, business, embedded systems, and computer-aided design. The final standardization of the C++ library now makes it easier to learn C++ and to use it across a wide variety of platforms. </P>
<P>Standardization improves portability and stability. You can build reliable applications faster, and maintain them with less cost and effort, using the C++ Standard Library.</P>
<BR>
<HR>
<A HREF="1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,63 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Product Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="1-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>1.2 Product Overview</H2>
<A NAME="121"><H3>1.2.1 Components</H3></A>
<A NAME="idx2"><!></A>
<P>The C++ Standard Library is a large and comprehensive collection of classes and functions for fine-grained, low-level programming. Within this library, you will find the following components:</P>
<UL>
<A NAME="idx3"><!></A>
<LI><P CLASS="LIST">The large set of data structures and algorithms formerly known as the Standard Template Library (STL)</P></LI>
<LI><P CLASS="LIST">An iostream facility</P></LI>
<LI><P CLASS="LIST">A locale facility</P></LI>
<LI><P CLASS="LIST">A templatized <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> class</P></LI>
<LI><P CLASS="LIST">A templatized <B><I><A HREF="../stdlibref/complex.html">complex</A></I></B> class for representing complex numbers</P></LI>
<LI><P CLASS="LIST">A <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> class optimized for handling numeric arrays</P></LI>
<LI><P CLASS="LIST">A uniform framework for describing the execution environment, using a template class named <B><I><A HREF="../stdlibref/numeric-limits.html">numeric_limits</A></I></B> and specializations for each fundamental datatype</P></LI>
<LI><P CLASS="LIST">Memory management features</P></LI>
<LI><P CLASS="LIST">Extensive support for national character sets</P></LI>
<LI><P CLASS="LIST">Exception handling features</P></LI>
</UL>
<A NAME="122"><H3>1.2.2 STL Not Object-Oriented</H3></A>
<P>The STL portion of the C++ Standard Library is not object-oriented. If you are accustomed to the benefits of object-oriented programming, their absence may necessitate some adjustment. Encapsulation of data and functionality in objects is a hallmark of object-oriented programming. In the C++ Standard Library, however, the data structures are separate from the algorithms you use to manipulate them.</P>
<P>This feature can provide a number of advantages, such as smaller source code, and the flexibility of using algorithms with C++ pointers and arrays as well as conventional objects. It can also lead to more efficient coding and faster execution, since it creates a direct, nuts-and-bolts approach to solving problems.</P>
<P>The main disadvantage of using the C++ Standard Library directly is increased risk of error. For example, the library's iterators must not be mismatched or invalidated, and iterators in multithreaded environments should be wrapped before being shared among threads. The templates can cause less precise diagnostics, and code that grows unexpectedly large. Experience with the library and your own compiler will help diminish these problems.</P>
<BR>
<HR>
<A HREF="1-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,70 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Usage Notes</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="1-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>1.3 Usage Notes</H2>
<A NAME="131"><H3>1.3.1 Compatibility Issues</H3></A>
<P>This implementation of the C++ Standard Library conforms to <I>ISO/IEC 14882:2003 -- International Standard for Information Systems -- Programming Language C++</I>. This release is source compatible with previous 2.x implementations.</P>
<P>1.x implementations of the library were based on <I>ANSI's Working Paper for Draft Proposed International Standard for Information Systems -- Programming Language C++</I>. The draft standard differs from the final standard in some areas. As a result, source written to 1.x implementations of the library will be incompatible with this implementation in these areas. See the readme file for details.</P>
<P>Please note that some compiler and library vendors have not yet implemented the whole range of language features defined by the ANSI/ISO standard. </P>
<BLOCKQUOTE><HR><B>
NOTE -- The C++ Standard Library is not yet fully implemented by all compilers. You may experience difficulty if you attempt to use features of the library that are unsupported by your compiler.
</B><HR></BLOCKQUOTE>
<P>In the <I>User's Guide</I>, we draw your attention to places in the code where this might be a problem. If your vendor is still in the process of meeting the standard, some of the techniques demonstrated in this <I>User's Guide</I> may not work. We include them anyway to demonstrate the full range of capabilities of the standard C++ language. Compilers will catch up, and this guide will be more useful to you if it is as complete as possible.</P>
<A NAME="132"><H3>1.3.2 The std Namespace</H3></A>
<P>Everything in the Apache C++ Standard Library is contained in the <SAMP>std</SAMP> namespace. You must specify a <SAMP>using</SAMP> directive or explicitly scope any name from the library.</P>
<P>To use the <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> class, for example, you could include one of the following <SAMP>using</SAMP> directives:</P>
<UL><PRE>
using namespace std; // Brings all names from std
// into current scope.
using std::vector; // Brings vector into
// current scope.
</PRE></UL>
<P>or explicitly scope <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> whenever it is used: </P>
<UL><PRE>
std::vector&lt;int&gt; v;
</PRE></UL>
<BLOCKQUOTE><HR><B>
NOTE -- To enhance this manual's readability, namespace scoping is usually omitted in the text. You should assume that everything in the Apache C++ Standard Library is scoped in namespace <SAMP>std</SAMP> unless otherwise stated.
</B><HR></BLOCKQUOTE>
<BR>
<HR>
<A HREF="1-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,69 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Documentation Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="1-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-5.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>1.4 Documentation Overview</H2>
<A NAME="141"><H3>1.4.1 Locations of Online Documentation</H3></A>
<A NAME="idx5"><!></A>
<P>To help you learn to use the <B>Apache C++ Standard Library</B> quickly and effectively, the library comes with the documentation described in <A HREF="1-4.html#Table&nbsp;1">Table&nbsp;1</A>. </P>
<P><B>All Apache C++ Standard Library documentation is installed online when you install your product. In addition, printed copies of user's guides may be purchased from your sales representative. </B></P>
<P><B>For easiest access to the Apache C++ Standard Library online documentation, open the file </B><SAMP><A HREF="../../index.html" TARGET="_top"><I>${TOPDIR}</I>/doc/index.html</A></SAMP><B> with your favorite browser, and follow the links to the documents you need.</B></P>
<P>Online documentation for the Apache C++ Standard Library is available at the locations shown in <A HREF="1-4.html#Table&nbsp;1">Table&nbsp;1</A>.</P>
<A NAME="idx6"><!></A>
<H4><A NAME="Table&nbsp;1">Table&nbsp;1: Locations of online documentation&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Document Format</B>
</td><td valign=top><B>Location</B>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">plain text</P>
</td><td valign=top><P CLASS="TABLE"><SAMP><I>${TOPDIR}</I></SAMP><SAMP>/README</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">HTML</P>
</td><td valign=top><P CLASS="TABLE">Single-point access to Apache C++ Standard Library HTML documentation:</P>
<P CLASS="TABLE"><SAMP><A HREF="../../index.html" TARGET="_top"><I>${TOPDIR}</I>/doc/index.html</A></SAMP></P>
<P CLASS="TABLE">Apache C++ Standard Library documentation:</P>
<P CLASS="TABLE"><I>User's Guide:</I> <SAMP><A HREF="../stdlibug/index.html" TARGET="_top"><I>${TOPDIR}</I>/doc/stdlibug/index.html</A></SAMP></P>
<P CLASS="TABLE"><I>Reference Guide:</I> <SAMP><A HREF="../stdlibref/index.html" TARGET="_top"><I>${TOPDIR}</I>/doc/stdlibref/index.html</A></SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">C++ source</P>
</td><td valign=top><P CLASS="TABLE"><SAMP><I>${TOPDIR}</I></SAMP><SAMP>/examples</SAMP></P>
</td></tr>
</TABLE>
<BR>
<HR>
<A HREF="1-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-5.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,98 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>About This Manual</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="1-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="II.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>1.5 About This Manual</H2>
<A NAME="151"><H3>1.5.1 Assumptions</H3></A>
<P>This manual assumes that you are familiar with the basic features of the C++ programming language. If you are new to C++, you may want to start with an introductory text, such as <I>The C++ Programming Language</I> by Bjarne Stroustrup (Addison-Wesley, 1997).</P>
<A NAME="152"><H3>1.5.2 Conventions</H3></A>
<A NAME="idx7"><!></A>
<P>This manual uses some distinctive terms and conventions. </P>
<P><I>Abbreviations</I> are common. Template abbreviations are very common, since the C++ Standard Library contains so many long names for class and function templates. For example, in the iostreams part of the documentation, <SAMP>fstream</SAMP> stands for <SAMP>template &lt;class charT, class traits&gt; class basic_fstream</SAMP>. The term <I>filestream </I>stands for the abstract notion of the file stream class template. <SAMP>badbit&nbsp;</SAMP>stands for the state flag <SAMP>std::ios_base::badbit</SAMP>.</P>
<P><I>Hierarchy diagrams</I> use the formal template declarations. In the hierarchy diagrams, the standard UML arrow:</P>
<P><IMG SRC="images/stdlibug-Overviewa.gif" WIDTH=240 HEIGHT=98></P>
<P>indicates that class <B><I>B</I></B> inherits from class <B><I>A</I></B>. </P>
<A NAME="idx8"><!></A>
<P>The term <I>algorithm</I> indicates functions in the generic algorithms portion of the C++ Standard Library. This is intended to avoid confusion with member functions, argument functions, and user-defined functions. </P>
<P>An <I>empty pair of parentheses</I> <SAMP>()</SAMP> follows function names and algorithm names, so as to avoid emphasizing their arguments. Arguments may be omitted for clarity.</P>
<P>An <I>underline character</I> <SAMP>_</SAMP> is used as a separator in both class names and function names. </P>
<P><I>Special fonts</I> set off class names, code samples, and special meanings, as shown in&nbsp;<A HREF="1-5.html#Table&nbsp;2">Table&nbsp;2</A>:.</P>
<H4><A NAME="Table&nbsp;2">Table&nbsp;2: Typographic conventions</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Convention</B>
</td><td valign=top><B>Purpose</B>
</td><td valign=top><B>Example</B>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>Courier</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Code, examples, function names, file names, directory names, and operating system commands.</P>
</td><td valign=top><P CLASS="TABLE"><SAMP>return result;</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><I>italic</I></P>
</td><td valign=top><P CLASS="TABLE">Conventional uses such as emphasis, titles, and new terms.</P>
</td><td valign=top><P CLASS="TABLE">A <I>comparison function object</I> is...</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><B>bold</B></P>
</td><td valign=top><P CLASS="TABLE">Conventional uses such as <B>emphasis</B>.</P>
<P CLASS="TABLE">Commands from an interface.</P>
</td><td valign=top><P CLASS="TABLE"><B>Always</B> read the manual.<br></P>
<P CLASS="TABLE">Click on the <B>OK</B> button.</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><B><I>bold italic</I></B></P>
</td><td valign=top><P CLASS="TABLE">Class names.</P>
</td><td valign=top><P CLASS="TABLE"><B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B></P>
</td></tr>
</TABLE>
<P>Throughout this guide, we use the character <SAMP>\</SAMP> to separate directory names. If you use UNIX, change <SAMP>\</SAMP> to <SAMP>/</SAMP>.</P>
<A NAME="153"><H3>1.5.3 Organization</H3></A>
<P>This manual is organized into eight parts:</P>
<UL>
<LI><P CLASS="LIST"><B><A HREF="I.html">Part&nbsp;I, "Introduction,"</A></B> provides overviews of the product, the documentation, and this manual, <I>The Apache C++ Standard Library User Guide</I>. </P></LI>
<LI><P CLASS="LIST"><B><A HREF="II.html">Part&nbsp;II, "Fundamentals,"</A></B> explains the fundamental C++ Standard Library concepts of iterators, functions, and predicates.</P></LI>
<LI><P CLASS="LIST"><B><A HREF="III.html">Part&nbsp;III, "Containers,"</A></B> gives an overview of the data structures called <I>containers</I>, and devotes a chapter to describing each container in detail, with an example. </P></LI>
<LI><P CLASS="LIST"><B><A HREF="IV.html">Part&nbsp;IV, "Algorithms,"</A></B> deals with the algorithms, devoting one chapter to the generic algorithms, and another to the generic algorithms specific to ordered collections. Within the two algorithm chapters, each kind of algorithm is explained in its own section, with an example and a reference to the file containing the complete source code. </P></LI>
<LI><P CLASS="LIST"><B><A HREF="V.html">Part&nbsp;V, "Special Techniques,"</A></B> describes techniques such as using allocators, building containers and generic algorithms, using the traits technique, and dealing with exceptions.</P></LI>
<LI><P CLASS="LIST"><B><A HREF="VI.html">Part&nbsp;VI, "Special Classes,"</A></B> devotes a chapter to each of the four unique classes <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B>, <B><I><A HREF="../stdlibref/complex.html">complex</A></I></B>, <B><I><A HREF="../stdlibref/numeric-limits.html">numeric_limits</A></I></B>, and <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B>.</P></LI>
<LI><P CLASS="LIST"><B><A HREF="VII.html">Part&nbsp;VII, "Locales,"</A></B> describes the basics of internationalization. It explains the differences between the C locale and the C++ locale. It defines a C++ locale and a facet, and tells how locales are created, composed, used, and replaced. It includes a complex example of a user-defined facet, which demonstrates how facets can be built and used in conjunction with iostreams.</P></LI>
<LI><P CLASS="LIST"><B><A HREF="VIII.html">Part&nbsp;VIII, "Iostreams,"</A></B> explains the C++ stream input and output facilities commonly called <I>iostreams</I>. Beginning chapters cover the iostreams facility, how it works, and how it should be used; also, the iostreams architecture, its components, and class hierarchy. Middle chapters cover the basic operation of iostreams, and both simple and advanced techniques for extending the iostreams framework. Final chapters describe the main differences between the C++ Standard Library iostreams, the traditional iostreams, and the implementation of iostreams in the Apache C++ Standard Library. </P></LI>
</UL>
<A NAME="154"><H3>1.5.4 Reading Suggestion</H3></A>
<P>The first time you read this manual it may be hard to know where to start. The container definitions form the heart of the library, but you can't really appreciate them without understanding the algorithms that so greatly extend their functionality. On the other hand, you can't really understand the algorithms without some appreciation of the containers. </P>
<P>A good approach is to read <B>Part II Fundamentals</B> carefully. Next, skim the definitions of the containers in <B>Part III Containers</B> and the descriptions of the algorithms in <B>Part IV Algorithms</B>, then go back and read these parts in more detail. You can then proceed to the more specialized areas of the manual.</P>
<BR>
<HR>
<A HREF="1-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="II.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

60
extern/stdcxx/4.2.1/doc/stdlibug/1.html vendored Normal file
View File

@@ -0,0 +1,60 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="I.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 1: Overview</H1>
<UL>
<UL><LI><A HREF="1-1.html">1.1 Welcome</A></LI></UL>
<UL><LI><A HREF="1-2.html">1.2 Product Overview</A></LI></UL>
<UL><UL><LI><A HREF="1-2.html#121">1.2.1 Components</A></LI></UL></UL>
<UL><UL><LI><A HREF="1-2.html#122">1.2.2 STL Not Object-Oriented</A></LI></UL></UL>
<UL><LI><A HREF="1-3.html">1.3 Usage Notes</A></LI></UL>
<UL><UL><LI><A HREF="1-3.html#131">1.3.1 Compatibility Issues</A></LI></UL></UL>
<UL><UL><LI><A HREF="1-3.html#132">1.3.2 The std Namespace</A></LI></UL></UL>
<UL><LI><A HREF="1-4.html">1.4 Documentation Overview</A></LI></UL>
<UL><UL><LI><A HREF="1-4.html#141">1.4.1 Locations of Online Documentation</A></LI></UL></UL>
<UL><LI><A HREF="1-5.html">1.5 About This Manual</A></LI></UL>
<UL><UL><LI><A HREF="1-5.html#151">1.5.1 Assumptions</A></LI></UL></UL>
<UL><UL><LI><A HREF="1-5.html#152">1.5.2 Conventions</A></LI></UL></UL>
<UL><UL><LI><A HREF="1-5.html#153">1.5.3 Organization</A></LI></UL></UL>
<UL><UL><LI><A HREF="1-5.html#154">1.5.4 Reading Suggestion</A></LI></UL></UL>
</UL>
<BR>
<HR>
<A HREF="I.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="1-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,50 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="10.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="10-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>10.1 Overview</H2>
<A NAME="idx183"><!></A>
<P>Most people have a good intuitive understanding of the <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> and <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> data abstractions based on experience with everyday objects. An excellent example of a stack is a pile of papers on a desk, or a stack of dishes in a cupboard. In both cases, the important characteristic is that the item on the top is most easily accessed. The easiest way to add a new item to the collection is to place it above all the current items in the stack. In this manner, an item removed from a stack is the item that has been most recently inserted into the stack; for example, the top piece of paper in the pile, or the top dish in the stack.</P>
<P>An everyday example of a queue, on the other hand, is a bank teller line, or a line of people waiting to enter a theater. Here new additions are made to the back of the queue, as new people enter the line, while items are removed from the front of the structure, as patrons enter the theater. The removal order for a queue is the opposite of that for a stack. In a queue, the item that is removed is the element that has been present in the queue for the longest period of time.</P>
<P>Among some groups of developers, a stack is referred to as a LIFO structure, and a queue is called a FIFO structure. The abbreviation <I>LIFO</I> stands for <I>Last In, First Out</I>. This means the first entry removed from a stack is the last entry that was inserted. The term <I>FIFO</I>, on the other hand, is short for <I>First In, First Out</I>. This means the first element removed from a queue is the first element that was inserted into the queue.</P>
<A NAME="idx184"><!></A>
<P>In the C++ Standard Library, both <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B>s and <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B>s are <I>adaptors</I>, built on top of other containers that actually hold the values. A <B><I>stack</I></B> can be built out of a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>, a <B><I><A HREF="../stdlibref/list.html">list</A></I></B>, or a <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>, while a <B><I>queue</I></B> can be built on top of either a <B><I>list</I></B> or a <B><I>deque</I></B>. Elements held by either a <B><I>stack</I></B> or <B><I>queue</I></B> must recognize both <SAMP>operator&lt;()</SAMP> and<SAMP> operator==()</SAMP>.</P>
<P>Because neither <B><I>stacks</I></B> nor <B><I>queues</I></B> define iterators, it is not possible to examine the elements of the collection except by removing the values one by one. The fact that these structures do not implement iterators also implies that most of the generic algorithms described in <A HREF="IV.html">Part&nbsp;IV</A> cannot be used with either data structure.</P>
<BR>
<HR>
<A HREF="10.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="10-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,176 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The stack Data Abstraction</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="10-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="10-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>10.2 The stack Data Abstraction</H2>
<A NAME="idx185"><!></A>
<P>As a data abstraction, a <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> is traditionally defined as any object that implements the operations defined in <A HREF="10-2.html#Table&nbsp;16">Table&nbsp;16</A>:</P>
<H4><A NAME="Table&nbsp;16">Table&nbsp;16: Stack operations</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Function</B>
</td><td valign=top><B>Implemented operation</B>
</td></tr>
<A NAME="idx186"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>empty()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Returns true if the collection is empty</P>
</td></tr>
<A NAME="idx187"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>size()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Returns number of elements in collection</P>
</td></tr>
<A NAME="idx188"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>top()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Returns (but does not remove) the topmost element in the stack</P>
</td></tr>
<A NAME="idx189"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>push(newElement)</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Pushes a new element onto the stack</P>
</td></tr>
<A NAME="idx190"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>pop()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Removes (but does not return) the topmost element from the stack</P>
</td></tr>
</TABLE>
<P>Note that removing the element at the top of the stack does not return a value. If the value of the element is important, you must retrieve the element before you remove the element.</P>
<A NAME="1021"><H3>10.2.1 Include Files</H3></A>
<A NAME="idx191"><!></A>
<P>Programs that use the <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> data abstraction should include the <SAMP>stack</SAMP> header:</P>
<UL><PRE>
#include &lt;stack&gt;
</PRE></UL>
<A NAME="1022"><H3>10.2.2 Declaration and Initialization of stack</H3></A>
<P>A stack can use either a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> or <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B> as the underlying container. When deciding which to use, consider the data which is to be stored. If the number of elements will vary widely, a <B><I>deque</I></B> may decrease the total amount of memory used when the <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> has few elements. A <B><I>vector</I></B> has less overhead, so may be more efficient in cases where the <B><I>stack</I></B> will tend to remain at approximately the same size. However, increasing the memory allocated to a <B><I>vector</I></B> is relatively slow, so a <B><I>vector</I></B> may be inefficient if the size of the container will tend to increase. These are, of course, generalized statements which may not apply to the problem at hand. In cases where efficiency of either speed or memory is important, you should try both underlying containers and compare the results. </P>
<P>The following are sample declarations for a stack:</P>
<UL><PRE>
std::stack&lt;int&gt; stackOne; // stack using deque
std::stack&lt;double, std::deque&lt;double&gt; &gt; stackTwo;
std::stack&lt;Part*, std::list&lt;Part*&gt; &gt; stackThree;
std::stack&lt;Customer, std::list&lt;Customer&gt; &gt; stackFour;
</PRE></UL>
<P>The last example creates a <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> from a user-defined type named <B><I>Customer</I></B>. </P>
<A NAME="idx192"><!></A>
<A NAME="1023"><H3>10.2.3 Example Program: An RPN Calculator</H3></A>
<A NAME="idx193"><!></A>
<P>A classic application of a <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> is in the implementation of this calculator. </P>
<BLOCKQUOTE><HR><B>
NOTE -- The executable version of this program is in the file calc.cpp.
</B><HR></BLOCKQUOTE>
<P>Input to the calculator consists of a standard <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> that represents an expression written in reverse polish notation (RPN). <I>Operands</I>, called <I>integer constants</I>, are pushed onto a <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> of values. As operators are encountered, the appropriate number of operands are popped off the stack, the operation is performed, and the result is pushed back onto the stack.</P>
<P>We can divide the development of our <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> simulation into two parts, a <I>calculator engine</I> and a <I>calculator program</I>. A <I>calculator engine</I> is concerned with the actual work involved in the simulation, but does not perform any input or output operations. The name is intended to suggest an analogy to a car engine or a computer processor: the mechanism performs the actual work, but the user of the mechanism does not normally directly interact with it. Wrapped around this is the <I>calculator program</I>, which interacts with the user and passes appropriate instructions to the calculator engine.</P>
<P>We can use the following class definition for our calculator engine. Inside the class declaration we define an enumerated <B><I><A HREF="../stdlibref/list.html">list</A></I></B> of values to represent each of the possible operators that the calculator is prepared to accept. We have made two simplifying assumptions: all operands will be integer values, and only binary operators will be handled.</P>
<UL><PRE>
class CalculatorEngine {
public:
enum binaryOperator { PLUS, MINUS, TIMES, DIVIDE };
int currentMemory () {
return data.top ();
}
void pushOperand (int value) {
data.push (value);
}
void doOperator (binaryOperator);
protected:
std::stack&lt; int, std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt; data;
};
</PRE></UL>
<P>The member function <SAMP>doOperator()</SAMP> performs the actual work. It pops values from the stack, performs the operation, then pushes the result back onto the stack:</P>
<UL><PRE>
void CalculatorEngine::doOperator (binaryOperator theOp) {
int right = data.top ();
data.pop ();
int left = data.top ();
data.pop ();
switch (theOp) {
case PLUS: data.push (left + right); break;
case MINUS: data.push (left - right); break;
case TIMES: data.push (left * right); break;
case DIVIDE: data.push (left / right); break;
}
}
</PRE></UL>
<P>(This code is simplified for demonstration purposes. A more robust program would check to see if the stack were empty before attempting to <SAMP>pop()</SAMP> elements from it.)</P>
<P>The main program reads values in reverse polish notation, invoking the calculator engine to do the actual work:</P>
<UL><PRE>
int main () {
std::cout &lt;&lt; "Calculator example program, from Chapter 8"
&lt;&lt; std::endl;
std::cout &lt;&lt; "Enter a legal RPN expression, "
&lt;&lt; "end with p q (print and quit)"
&lt;&lt; std::endl;
char c;
int intval;
CalculatorEngine calc;
while (std::cin &gt;&gt; c)
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
std::cin.putback (c);
std::cin &gt;&gt; intval;
calc.pushOperand (intval);
break;
case '+':
calc.doOperator (CalculatorEngine::PLUS); break;
case '-':
calc.doOperator (CalculatorEngine::MINUS); break;
case '*':
calc.doOperator (CalculatorEngine::TIMES); break;
case '/':
calc.doOperator (CalculatorEngine::DIVIDE); break;
case 'p':
std::cout &lt;&lt; calc.currentMemory () &lt;&lt; std::endl;
case 'q':
std::cout &lt;&lt; "End calculator program" &lt;&lt; std::endl;
return 0; // quit program
}
return 0;
}
</PRE></UL>
<BR>
<HR>
<A HREF="10-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="10-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,183 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The queue Data Abstraction</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="10-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="11.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>10.3 The queue Data Abstraction</H2>
<A NAME="idx194"><!></A>
<P>As a data abstraction, a <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> is traditionally defined as any object that implements the following operations given in <A HREF="10-3.html#Table&nbsp;17">Table&nbsp;17</A>:</P>
<H4><A NAME="Table&nbsp;17">Table&nbsp;17: Queue operations</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Function</B>
</td><td valign=top><B>Implemented operation</B>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>empty()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Returns <SAMP>true</SAMP> if the collection is empty</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>size()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Returns number of elements in collection</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>front()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Returns (but does not remove) the element at the front of the queue </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>back()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Returns (but does not remove) the element at the end of the queue </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>push(newElement)</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Pushes a new element on to the end of the queue </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>pop()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Removes (but does not return) the element at the front of the queue</P>
</td></tr>
</TABLE>
<P>Note that removing the element at the front of the <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> does not return a value. If the value of the element is important, you must retrieve the element before you remove the element</P>
<A NAME="1031"><H3>10.3.1 Include Files</H3></A>
<A NAME="idx195"><!></A>
<P>Programs that use the <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> data abstraction should include the <SAMP>queue</SAMP> header file:</P>
<UL><PRE>
#include &lt;queue&gt;
</PRE></UL>
<A NAME="idx196"><!></A>
<A NAME="1032"><H3>10.3.2 Declaration and Initialization of queue</H3></A>
<A NAME="idx197"><!></A>
<P>A declaration for a <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> must specify the element type, and can also specify the container that will hold the values. For a <B><I>queue</I></B> the default container is a <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>, but a list can also be used. The <B><I><A HREF="../stdlibref/list.html">list</A></I></B> version is generally smaller, while the <B><I>deque</I></B> version may be slightly faster. The following are sample declarations for a <B><I>queue</I></B>:</P>
<UL><PRE>
std::queue&lt;int, list&lt;int&gt; &gt; queueOne;
std::queue&lt;double&gt; queueTwo; // uses a deque
std::queue&lt;Part*, list&lt;Part*&gt; &gt; queueThree;
std::queue&lt;Customer, list&lt;Customer&gt; &gt; queueFour;
</PRE></UL>
<P>The last example creates a <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> of a user-defined type named <B><I>Customer</I></B>. As with the <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B> container, all objects stored in a <B><I>queue</I></B> must understand <SAMP>operator&lt;()</SAMP> and <SAMP>operator==()</SAMP>.</P>
<P>Because the <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> does not implement an iterator, few of the generic algorithms described in <A HREF="IV.html">Part&nbsp;IV</A> apply to <B><I>queue</I></B>s.</P>
<A NAME="idx198"><!></A>
<A NAME="1033"><H3>10.3.3 Example Program: Bank Teller Simulation</H3></A>
<BLOCKQUOTE><HR><B>
NOTE -- The complete version of the bank teller simulation program is in teller.cpp.
</B><HR></BLOCKQUOTE>
<A NAME="idx199"><!></A>
<P>Queues are often found in businesses, such as supermarkets or banks. Suppose you are the manager of a bank, and you need to determine how many tellers to have working during certain hours. You decide to create a computer simulation, basing your simulation on certain observed behavior. For example, you note that during peak hours there is a ninety percent chance that a customer will arrive every minute.</P>
<P>We create a simulation by first defining objects to represent both customers and tellers. For customers, the information we want to know is the average amount of time they spend waiting in line. Thus, customer objects simply maintain two integer data members: the time they arrive in line, and the time they spend at the counter. The latter is a value randomly selected between 2 and 8.</P>
<UL><PRE>
class Customer
{
public:
int arrivalTime;
int processTime;
Customer (int at = 0)
: arrivalTime (at),
processTime (2 + irand () % 6) {}
// are we done with our transaction?
bool done () {
return --processTime &lt; 0;
}
// order by arrival time
bool operator&lt; (const Customer&amp; c) const {
return arrivalTime &lt; c.arrivalTime;
}
};
</PRE></UL>
<P>Because objects can only be stored in a standard <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> if they can be compared for ordering, it is necessary to define <SAMP>operator&lt;()</SAMP> for customers. Customers can also tell us when they are done with their transactions. Tellers are either busy servicing customers, or they are free. Thus, each teller value holds two data members: a customer, and a boolean flag. Tellers define a member function to answer whether they are free or not, as well as a member function that is invoked when they start servicing a customer.</P>
<UL><PRE>class Teller
{
public:
Teller (): free (true) { }
bool isFree () { // are we free to service new customer?
if (free)
return true;
if (customer.done())
free = true;
return free;
}
// start serving new customer
void addCustomer (const Customer &amp;c) {
customer = c;
free = false;
}
private:
bool free;
Customer customer;
};
</PRE></UL>
<P>The main program, then, is a large loop cycling once each simulated minute. The probability is 0.9 that each minute a new customer is entered into the queue of waiting customers. Each teller is polled, and if any are free they take the next customer from the queue. Counts are maintained of the number of customers serviced and the total time they spent in queue. From these two values we can determine, following the simulation, the average time a customer spent waiting in the line.</P>
<UL><PRE>
int main ()
{
const int numberOfTellers = 5;
const int numberOfMinutes = 60;
double totalWait = 0;
int numberOfCustomers = 0;
std::vector&lt;Teller&gt; teller (numberOfTellers);
std::queue&lt;Customer&gt; line;
for (int t = 0; t &lt; numberOfMinutes; t++) {
if (irand() % 10 &lt; 9)
line.push (Customer (t));
for (int i = 0; i &lt; numberOfTellers; i++) {
if (teller[i].isFree () &amp;&amp; !line.empty ()) {
Customer&amp; frontCustomer = line.front ();
numberOfCustomers++;
totalWait += t - frontCustomer.arrivalTime;
teller[i].addCustomer (frontCustomer);
line.pop ();
}
}
}
std::cout &lt;&lt; "average wait: "
&lt;&lt; (totalWait / numberOfCustomers) &lt;&lt; std::endl;
}
</PRE></UL>
<P>By executing the program several times, using various values for the number of tellers, the manager can determine the smallest number of tellers that can service the customers while maintaining the average waiting time at an acceptable level.</P>
<BR>
<HR>
<A HREF="10-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="11.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,55 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The Container Adaptors stack and queue</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="9-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="10-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 10: The Container Adaptors stack and queue</H1>
<UL>
<UL><LI><A HREF="10-1.html">10.1 Overview</A></LI></UL>
<UL><LI><A HREF="10-2.html">10.2 The stack Data Abstraction</A></LI></UL>
<UL><UL><LI><A HREF="10-2.html#1021">10.2.1 Include Files</A></LI></UL></UL>
<UL><UL><LI><A HREF="10-2.html#1022">10.2.2 Declaration and Initialization of stack</A></LI></UL></UL>
<UL><UL><LI><A HREF="10-2.html#1023">10.2.3 Example Program: An RPN Calculator</A></LI></UL></UL>
<UL><LI><A HREF="10-3.html">10.3 The queue Data Abstraction</A></LI></UL>
<UL><UL><LI><A HREF="10-3.html#1031">10.3.1 Include Files</A></LI></UL></UL>
<UL><UL><LI><A HREF="10-3.html#1032">10.3.2 Declaration and Initialization of queue</A></LI></UL></UL>
<UL><UL><LI><A HREF="10-3.html#1033">10.3.3 Example Program: Bank Teller Simulation</A></LI></UL></UL>
</UL>
<BR>
<HR>
<A HREF="9-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="10-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,56 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The priority queue Data Abstraction</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="11.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="11-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>11.1 The priority queue Data Abstraction</H2>
<A NAME="idx200"><!></A>
<P>A <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> is a data structure useful in problems where you need to rapidly and repeatedly find and remove the largest element from a collection of values. An everyday example of a priority queue is the <I>to do</I> list of tasks waiting to be performed that most of us maintain to keep ourselves organized. Some jobs, such as <I>clean desktop</I>, are not imperative and can be postponed arbitrarily. Other tasks, such as <I>finish report by Monday</I> or <I>buy flowers for anniversary</I>, are time-crucial and must be addressed more rapidly. Thus, we sort the tasks waiting to be accomplished in order of their importance, or perhaps based on a combination of their critical importance, their long term benefit, and the fun we will have doing them, and choose the most pressing.</P>
<P>A more computer-related example of a priority queue is the list of pending processes maintained by an operating system, where the value associated with each element is the priority of the job. For example, it may be necessary to respond rapidly to a key pressed at a terminal before the data is lost when the next key is pressed. On the other hand, the process of copying a listing to a queue of output waiting to be handled by a printer is something that can be postponed for a short period, as long as it is handled eventually. By maintaining processes in a priority queue, those jobs with urgent priority are executed prior to any jobs with less urgent requirements.</P>
<A NAME="idx201"><!></A>
<P>Simulation programs use a priority queue of <I>future events</I>. The simulation maintains a virtual <I>clock</I>, and each event has an associated time when the event will take place. In such a collection, the element with the smallest time value is the next event that should be simulated. These are only a few instances of the types of problems for which a <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> is a useful tool. You probably have encountered others, or you soon will.</P>
<P>Some developers may feel the term priority <I>queue</I> is a misnomer. The data structure is not a <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B> in the sense that we used the term in <A HREF="10.html">Chapter&nbsp;10</A>, since it does not return elements in a strict first-in, first-out sequence. Nevertheless, the name is now firmly associated with this particular datatype.</P>
<A NAME="1111"><H3>11.1.1 Include Files</H3></A>
<A NAME="idx202"><!></A>
<P>Programs that use the priority queue data abstraction should include the <SAMP>queue</SAMP> header file:</P>
<UL><PRE>
#include &lt;queue&gt;
</PRE></UL>
<BR>
<HR>
<A HREF="11.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="11-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,98 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The priority queue Operations</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="11-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="11-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>11.2 The priority queue Operations</H2>
<A NAME="idx203"><!></A>
<P>A specialization of the <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> class template holds elements of type <SAMP>T</SAMP> and implements the five operations given in <A HREF="11-2.html#Table&nbsp;18">Table&nbsp;18</A>:</P>
<H4><A NAME="Table&nbsp;18">Table&nbsp;18: priority_queue operations</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Function</B>
</td><td valign=top><B>Implemented operation</B>
</td></tr>
<A NAME="idx204"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>push(T)</SAMP></P>
</td><td valign=top><P CLASS="TABLE"> Adds a new value to the collection being maintained</P>
</td></tr>
<A NAME="idx205"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>top()</SAMP></P>
</td><td valign=top><P CLASS="TABLE"> Returns a reference to the smallest element in the collection</P>
</td></tr>
<A NAME="idx206"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>pop()</SAMP></P>
</td><td valign=top><P CLASS="TABLE"> Deletes the smallest element from the collection</P>
</td></tr>
<A NAME="idx207"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>size()</SAMP></P>
</td><td valign=top><P CLASS="TABLE"> Returns the number of elements in the collection</P>
</td></tr>
<A NAME="idx208"><!></A>
<tr><td valign=top><P CLASS="TABLE"><SAMP>empty()</SAMP></P>
</td><td valign=top><P CLASS="TABLE"> Returns true if the collection is empty </P>
</td></tr>
</TABLE>
<P>Elements of type <SAMP>T</SAMP> must be comparable to each other, either through the use of the default less-than operator, <SAMP>operator&lt;()</SAMP>, or through a comparison function passed either as a template argument or as an optional argument on the constructor. The latter form will be illustrated in the example program provided later in this chapter. As with all the containers in the C++ Standard Library, there are several constructors. The <I>default constructor</I> requires either no arguments or the optional comparison function. An <I>alternative constructor</I> takes two iterators and initializes the values in the container from the range the iterators define. An optional third argument can be used to define the comparison function.</P>
<P>The <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> datatype is built on top of a container class, which is the structure actually used to maintain the values in the collection. There are two containers in the C++ Standard Library that can be used to construct <B><I>priority_queues</I></B>: <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B><I>s</I> or <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B><I>s</I>. By default, a <B><I>priority_queue</I></B> will use <B><I>vector</I></B>.</P>
<A NAME="1121"><H3>11.2.1 Declaration and Initialization of priority queue</H3></A>
<A NAME="idx209"><!></A>
<P>The following illustrates the declaration of several <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B>s:</P>
<UL><PRE>
// minimal case -- uses std::vector&lt;int&gt; and std::less&lt;int&gt;
std::priority_queue&lt;int&gt; queue_one;
std::priority_queue&lt;int, std::vector&lt;int&gt;, std::greater&lt;int&gt; &gt;
queue_two;
std::priority_queue&lt;double, std::deque&lt;double&gt; &gt;
queue_three(aList.begin(), aList.end());
std::priority_queue&lt;myData, std::vector&lt;myData&gt; &gt;
queue_four(myComparison);
std::priority_queue&lt;myData, std::deque&lt;myData&gt; &gt;
queue_five(aVector.begin(), aVector.end(), myComparison);
</PRE></UL>
<A NAME="idx210"><!></A>
<P>When deciding whether to use a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> or <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B> as the underlying container, consider the data which is to be stored. The default, <B><I>vector</I></B>, performs quite well for most cases. If the number of elements will vary, a <B><I>deque</I></B> will use less memory when the <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> has few elements. A <B><I>vector</I></B> has less overhead, so may be more efficient in cases where the <B><I>priority_queue</I></B> will tend to remain at approximately the same size. However, increasing the memory allocated to a <B><I>vector</I></B> may require copying the elements into newly allocated space. Copying takes time, so a <B><I>vector</I></B> may be inefficient if the size of the <B><I>priority_queue</I></B> will tend to increase. These are, of course, generalized statements which may not apply to the problem at hand. In cases where performance or memory consumption is important, you should try both underlying containers and compare the results.</P>
<P>Because the <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> data structure does not itself know how to construct iterators, very few of the algorithms noted in <A HREF="13.html">Chapter&nbsp;13</A> can be used with <B><I>priority_queue</I></B>s. Instead of iterating over values, a typical algorithm that uses a <B><I>priority_queue</I></B> constructs a loop, which repeatedly pulls values from the structure (using the <SAMP>top()</SAMP> and <SAMP>pop()</SAMP> member functions) until the collection becomes empty (tested using the <SAMP>empty()</SAMP> member function). The example program described in <A HREF="11-3.html">Section&nbsp;11.3</A> illustrates this use.</P>
<A NAME="idx211"><!></A>
<P>A <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> is implemented by internally building a data structure called a <I>heap. </I>Abstractly, a <I>heap</I> is a binary tree in which the value associated with every node is smaller than or equal to the value associated with either child node. Details of the algorithms used in manipulating<I> heaps</I> will not be discussed here, but can be found in most textbooks on data structures.</P>
<BR>
<HR>
<A HREF="11-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="11-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,253 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Example Program: Event-Driven Simulation</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="11-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="12.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>11.3 Example Program: Event-Driven Simulation</H2>
<A NAME="idx212"><!></A>
<A NAME="idx213"><!></A>
<P>An extended example will now illustrate one of the more common uses of a priority_queues, which is to support the construction of a simulation model. A <I>discrete event-driven simulation</I> is a popular simulation technique. Objects in the simulation model objects in the real world, and are programmed to react as much as possible as the real objects would react. A <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> is used to store a representation of <I>events</I> that are waiting to happen. This queue is stored in order, based on the time the event should occur, so the smallest element will always be the next event to be modeled. As an event occurs, it can spawn other events. These subsequent events are placed into the queue as well. Execution continues until all events have been processed.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The complete version of the ice cream store simulation program is in icecream.cpp.
</B><HR></BLOCKQUOTE>
<P>Events can be represented as subclasses of a base class, which we call <B><I>event</I></B>. The base class simply records the time at which the event will take place. A pure virtual function named <SAMP>processEvent</SAMP> is invoked to execute the event:</P>
<UL><PRE>
class event {
public:
// Construct sets time of event.
event (unsigned int t) : time (t)
{ }
// Execute event by invoking this method.
virtual void processEvent () = 0;
const unsigned int time;
};
</PRE></UL>
<A NAME="idx214"><!></A>
<P>The simulation queue needs to maintain a collection of different types of events, sometimes called a <I>heterogeneous</I> collection. Each different form of event is represented by a subclass of class <B><I>event</I></B>, but not all <B><I>event</I></B>s have the same exact type. For this reason the collection must store <I>pointers</I> to <B><I>event</I></B>s, instead of the events themselves. Since the containers maintain pointers to values, not the values themselves, the programmer is responsible for managing the memory for the objects being manipulated.</P>
<P>Since comparison of pointers cannot be specialized on the basis of the pointer types, we must instead define a new comparison function for pointers to events. In the C++ Standard Library we do this by defining a new structure whose sole purpose is to define the function invocation <SAMP>operator()()</SAMP> in the appropriate fashion. Since in this particular example we want to use the <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> to return the smallest element each time, rather than the largest, the order of the comparison is reversed, as follows:</P>
<UL><PRE>
struct eventComparator {
bool operator() (const event * left, const event * right) const {
return left-&gt;time &gt; right-&gt;time;
}
};
</PRE></UL>
<BLOCKQUOTE><HR><B>
NOTE -- We use a priority queue as a structure for quickly discovering the smallest element in a sequence. If, instead, your problem requires the discovery of the largest element, there are various possibilities. One is to supply the inverse operator as either a template argument or the optional comparison function argument to the constructor. If you are defining the comparison argument as a function, as in the example problem, another solution is to simply invert the comparison test.
</B><HR></BLOCKQUOTE>
<P>We are now ready to define the class <B><I>simulation</I></B>, which provides the structure for the simulation activities. The class <B><I>simulation</I></B> provides two functions: the first is used to insert a new event into the queue, while the second runs the simulation. A data member is also provided to hold the current simulation <B><I>time</I></B>:</P>
<UL><PRE>
class simulation {
public:
simulation () : time (0), eventQueue ()
{}
void run ();
void scheduleEvent (event * newEvent) {
eventQueue.push (newEvent);
}
unsigned int time;
protected:
std::priority_queue&lt;event*,
std::vector&lt;event *, std::allocator&lt;event*&gt; &gt;,
eventComparator&gt; eventQueue;
};
</PRE></UL>
<P>Notice the declaration of the <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> used to hold the pending <B><I>event</I></B>s. In this case we are using a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> as the underlying container, but we could just as easily have used a <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>. </P>
<P>The heart of the simulation is the member function<SAMP> run()</SAMP>, which defines the event loop. This procedure makes use of three of the five <B><I><A HREF="../stdlibref/priority-queue.html">priority_queue</A></I></B> operations, namely <SAMP>top()</SAMP>, <SAMP>pop()</SAMP>, and <SAMP>empty().</SAMP> It is implemented as follows:</P>
<UL><PRE>
void simulation::run () {
while (! eventQueue.empty ()) {
event * nextEvent = eventQueue.top ();
eventQueue.pop ();
time = nextEvent-&gt;time;
nextEvent-&gt;processEvent ();
delete nextEvent;
}
}
</PRE></UL>
<A NAME="idx215"><!></A>
<A NAME="1131"><H3>11.3.1 Example Program: An Ice Cream Store Simulation</H3></A>
<A NAME="idx216"><!></A>
<P>To illustrate the use of our simulation framework, this example program gives a simple simulation of an ice cream store. Such a simulation might be used, for example, to determine the optimal number of chairs that should be provided, based on assumptions such as the frequency with which customers arrive, the length of time they stay, and so on.</P>
<P>Our store simulation is based around a subclass of class <B><I>simulation</I></B>, defined as follows:</P>
<UL><PRE>
class storeSimulation : public simulation {
public:
storeSimulation () : simulation (), freeChairs (35), profit (0.0)
{ }
bool canSeat (unsigned int numberOfPeople);
void order (unsigned int numberOfScoops);
void leave (unsigned int numberOfPeople);
// Data fields.
unsigned int freeChairs;
double profit;
} theSimulation;
</PRE></UL>
<P>There are three basic activities associated with the store: arrival, ordering and eating, and leaving. This is reflected not only in the three member functions defined in the <B><I>simulation</I></B> class, but in three separate subclasses of <B><I>event</I></B>.</P>
<P>The member functions associated with the store simply record the activities taking place, producing a log that can later be studied to evaluate the simulation.</P>
<UL><PRE>
bool storeSimulation::canSeat (unsigned int numberOfPeople) {
std::cout &lt;&lt; "Time: " &lt;&lt; time;
std::cout &lt;&lt; " group of " &lt;&lt; numberOfPeople &lt;&lt; " customers arrives";
if (numberOfPeople &lt; freeChairs) {
std::cout &lt;&lt; " is seated\n";
freeChairs -= numberOfPeople;
return true;
}
else {
std::cout &lt;&lt; " no room, they leave\n";
return false;
}
}
void storeSimulation::order (unsigned int numberOfScoops) {
std::cout &lt;&lt; "Time: " &lt;&lt; time &lt;&lt; " serviced order for "
&lt;&lt; numberOfScoops &lt;&lt; '\n';
profit += 0.35 * numberOfScoops;
}
void storeSimulation::leave (unsigned int numberOfPeople) {
std::cout &lt;&lt; "Time: " &lt;&lt; time &lt;&lt; " group of size "
&lt;&lt; numberOfPeople &lt;&lt; " leaves\n";
freeChairs += numberOfPeople;
}
</PRE></UL>
<A NAME="idx217"><!></A>
<P>As we noted already, each activity is matched by a subclass of <B><I>event</I></B>. Each subclass of <B><I>event</I></B> includes an integer data member, which represents the size of a group of customers. The arrival event occurs when a group enters. When executed, the arrival event creates and installs a new instance of the order event. The function <SAMP>randomInteger()</SAMP> is used to compute a random integer between 1 and the argument value (see <A HREF="2-2.html#225">Section&nbsp;2.2.5</A>).</P>
<UL><PRE>
class arriveEvent : public event {
public:
arriveEvent (unsigned int t, unsigned int groupSize)
: event (t), size (groupSize)
{ }
virtual void processEvent ();
private:
unsigned int size;
};
void arriveEvent::processEvent () {
if (theSimulation.canSeat (size))
theSimulation.scheduleEvent
(new orderEvent (time + 1 + irand (4), size));
}
</PRE></UL>
<P>An order event similarly spawns a leave event:</P>
<UL><PRE>
class orderEvent : public event {
public:
orderEvent (unsigned int t, unsigned int groupSize)
: event (t), size (groupSize)
{ }
virtual void processEvent ();
private:
unsigned int size;
};
void orderEvent::processEvent () {
// Each person orders some number of scoops.
for (unsigned int i = 0; i &lt; size; i++)
theSimulation.order (1 + irand (4));
// Then we schedule the leave event.
theSimulation.scheduleEvent
(new leaveEvent (time + 1 + irand (10), size));
}
</PRE></UL>
<P>Finally, leave events free up chairs, but do not spawn any new events:</P>
<UL><PRE>
class leaveEvent : public event
{
public:
leaveEvent (unsigned int t, unsigned int groupSize)
: event (t), size (groupSize)
{ }
virtual void processEvent ();
private:
unsigned int size;
};
void leaveEvent::processEvent () {
theSimulation.leave (size);
}
</PRE></UL>
<P>To run the simulation we simply create some number of initial events (say, 30 minutes worth), then invoke the <SAMP>run()</SAMP> member function:</P>
<UL><PRE>
int main () {
std::cout &lt;&lt; "Ice Cream Store simulation from Chapter 9\n";
// Load queue with some number of initial events.
for (unsigned t = 0; t &lt; 20; t += irand (6)) {
std::cout &lt;&lt; "pumping queue with event " &lt;&lt; t &lt;&lt; '\n';
theSimulation.scheduleEvent (new arriveEvent (t, 1 + irand (4)));
}
// Run the simulation.
theSimulation.run ();
std::cout &lt;&lt; "Total profits " &lt;&lt; theSimulation.profit
&lt;&lt; "\nEnd of ice cream store simulation\n";
return 0;
}
</PRE></UL>
<BR>
<HR>
<A HREF="11-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="12.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,52 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The Container Adaptor priority queue</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="10-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="11-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 11: The Container Adaptor priority queue</H1>
<UL>
<UL><LI><A HREF="11-1.html">11.1 The priority queue Data Abstraction</A></LI></UL>
<UL><UL><LI><A HREF="11-1.html#1111">11.1.1 Include Files</A></LI></UL></UL>
<UL><LI><A HREF="11-2.html">11.2 The priority queue Operations</A></LI></UL>
<UL><UL><LI><A HREF="11-2.html#1121">11.2.1 Declaration and Initialization of priority queue</A></LI></UL></UL>
<UL><LI><A HREF="11-3.html">11.3 Example Program: Event-Driven Simulation</A></LI></UL>
<UL><UL><LI><A HREF="11-3.html#1131">11.3.1 Example Program: An Ice Cream Store Simulation</A></LI></UL></UL>
</UL>
<BR>
<HR>
<A HREF="10-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="11-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,67 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The string Abstraction</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="12.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="12-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>12.1 The string Abstraction</H2>
<A NAME="idx218"><!></A>
<P>A <I>string</I> is basically a sequence of characters that can be indexed. In fact, although a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> is not declared as a subclass of <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>, almost all the <B><I>vector</I></B> operators discussed in <A HREF="5.html">Chapter&nbsp;5</A> can be applied to <B><I>string</I></B> values. Indeed, a string qualifies as a <B><I>sequence</I></B> container type. However, a <B><I>string</I></B> is also a much more abstract quantity. In addition to simple <B><I>vector</I></B> operators, the <B><I>string</I></B> datatype provides a number of useful and powerful high level operations.</P>
<A NAME="idx219"><!></A>
<P>In the C++ Standard Library, a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> is actually a template class, named <B><I><A HREF="../stdlibref/basic-string.html">basic_string</A></I></B>. The template argument represents the type of character that will be held by the <B><I>string</I></B> container. By defining strings in this fashion, the C++ Standard Library not only provides facilities for manipulating sequences of 8-bit characters, but also for manipulating other types of character-like sequences, such as 16-bit wide characters. The datatypes <B><I>string</I></B> and <B><I><A HREF="../stdlibref/wstring.html">wstring</A></I></B> (for wide string) are simply typedefs of <B><I>basic_string</I></B>, defined as follows:</P>
<UL><PRE>
typedef std::basic_string&lt;char, std::char_traits&lt;char&gt;,
std::allocator&lt;char&gt; &gt; std::string;
typedef std::basic_string&lt;wchar_t, std::char_traits&lt;wchar_t&gt;,
std::allocator&lt;wchar_t&gt; &gt; std::wstring;
</PRE></UL>
<BLOCKQUOTE><HR><B>
NOTE -- In the remainder of this chapter, we refer to the string datatype, but all the operations we introduce are equally applicable to wide strings.
</B><HR></BLOCKQUOTE>
<P>As we have already noted, a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> is similar in many ways to a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> of characters. Like the <B><I>vector</I></B> datatype, a <B><I>string</I></B> is associated with two sizes. The first represents the <I>number of characters</I> currently being stored in the string; the second is the capacity, the <I>maximum number of characters</I> that can potentially be stored in a <B><I>string</I></B> without reallocation of a new internal buffer. </P>
<P>As in the <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> datatype, the capacity of a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> is a dynamic quantity. When <B><I>string</I></B> operations cause the number of characters being stored in a <B><I>string</I></B> value to exceed the capacity of the <B><I>string</I></B>, a new internal buffer is allocated and initialized with the <B><I>string</I></B> values, and the capacity of the <B><I>string</I></B> is increased. All this occurs behind the scenes, requiring no interaction with the programmer.</P>
<A NAME="1211"><H3>12.1.1 Include Files</H3></A>
<A NAME="idx220"><!></A>
<P>Programs that use <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>s must include the <SAMP>string</SAMP> header file:</P>
<UL><PRE>
#include &lt;string&gt;
</PRE></UL>
<BR>
<HR>
<A HREF="12.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="12-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,214 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>string Operations</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="12-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="12-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>12.2 string Operations</H2>
<P>In the following sections, we'll examine the C++ Standard Library operations used to create and manipulate <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>s.</P>
<A NAME="1221"><H3>12.2.1 Declaration and Initialization of string</H3></A>
<A NAME="idx221"><!></A>
<P>The simplest form of declaration for a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> simply names a new variable, or names a variable along with the initial value for the <B><I>string</I></B>. This form was used extensively in the example graph program given in <A HREF="9-3.html#932">Section&nbsp;9.3.2</A>. A copy constructor also permits a <B><I>string</I></B> to be declared that takes its value from a previously defined <B><I>string</I></B>:</P>
<UL><PRE>
std::string s1;
std::string s2("a string");
std::string s3 = "initial value";
std::string s4(s3);
</PRE></UL>
<P>In these simple cases the capacity is initially exactly the same as the number of characters being stored. An alternative constructor lets you set the capacity and initialize the <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> with repeated copies of a single character value:</P>
<UL><PRE>
std::string s7(10, '\n'); // holds ten newline characters
</PRE></UL>
<P>Finally, like all the container classes in the C++ Standard Library, a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> can be initialized using a pair of <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s. The sequence denoted by the <B><I>iterator</I></B>s must have the appropriate type of elements.</P>
<UL><PRE>
string s8 (aList.begin(), aList.end());
</PRE></UL>
<A NAME="1222"><H3>12.2.2 Resetting Size and Capacity</H3></A>
<A NAME="idx222"><!></A>
<P>As with the <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> datatype, the member function <SAMP>size()</SAMP> yields the current size of a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>, and the current capacity is returned by <SAMP>capacity()</SAMP>. The latter can be changed by a call on the <SAMP>reserve()</SAMP> member function, which adjusts the capacity if necessary so that the string can hold at least as many elements as specified by the argument. The member function <SAMP>max_size()</SAMP> returns the maximum string size that can be allocated: </P>
<UL><PRE>
std::cout &lt;&lt; s6.size() &lt;&lt; std::endl;
std::cout &lt;&lt; s6.capacity() &lt;&lt; std::endl;
s6.reserve(200); // change capacity to 200
std::cout &lt;&lt; s6.capacity() &lt;&lt; std::endl;
std::cout &lt;&lt; s6.max_size() &lt;&lt; std::endl;
</PRE></UL>
<A NAME="idx223"><!></A>
<P>The member function <SAMP>length()</SAMP> is simply a synonym for <SAMP>size()</SAMP>. The member function <SAMP>resize()</SAMP> changes the size of a string, either truncating characters from the end or inserting new characters. The optional second argument for <SAMP>resize()</SAMP> can be used to specify the character inserted into the newly created character positions.</P>
<UL><PRE>
s7.resize(15, '\t'); // add tab characters at end
std::cout &lt;&lt; s7.length() &lt;&lt; std::endl; // size should now be 15
</PRE></UL>
<A NAME="idx224"><!></A>
<P>The member function <SAMP>empty()</SAMP> returns <SAMP>true</SAMP> if the string contains no characters, and is generally faster than testing the length against a zero constant.</P>
<UL><PRE>
if (s1.empty())
std::cout &lt;&lt; "string is empty" &lt;&lt; std::endl;
</PRE></UL>
<A NAME="1223"><H3>12.2.3 Assignment, Append, and Swap</H3></A>
<A NAME="idx225"><!></A>
<P>A string variable can be assigned the value of either another string, a literal C-style character array, or an individual character:</P>
<UL><PRE>
s1 = s2;
s2 = "a new value";
s3 = 'x';
</PRE></UL>
<A NAME="idx226"><!></A>
<P>The operator <SAMP>+=</SAMP> can also be used with any of these three forms of argument, and specifies that the value on the right-hand side should be <I>appended </I>to the end of the current string value.</P>
<UL><PRE>
s3 += "yz"; // s3 is now xyz
</PRE></UL>
<A NAME="idx227"><!></A>
<P>The more general <SAMP>assign()</SAMP> and <SAMP>append()</SAMP> member functions let you specify a subset of the right-hand side to be assigned to or appended to the receiver. Two arguments, <SAMP>pos</SAMP> and <SAMP>n</SAMP>, indicate that the <SAMP>n</SAMP> values following position <SAMP>pos</SAMP> should be assigned or appended:</P>
<UL><PRE>
s4.assign(s2, 0, 3); // assign first three characters
s4.append(s5, 2, 3); // append characters 2, 3 and 4
</PRE></UL>
<P>The addition<SAMP> operator+()</SAMP> is used to form the catenation of two strings. The <SAMP>operator+()</SAMP> creates a copy of the left argument, then appends the right argument to this value:</P>
<UL><PRE>
std::cout &lt;&lt; (s2 + s3) &lt;&lt; std::endl; // output catenation of
// s2 and s3
</PRE></UL>
<A NAME="idx228"><!></A>
<P>As with all the containers in the C++ Standard Library, the contents of two <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>s can be exchanged using the <SAMP>swap()</SAMP> member function:</P>
<UL><PRE>
s5.swap(s4); // exchange s4 and s5
</PRE></UL>
<A NAME="1224"><H3>12.2.4 Character Access</H3></A>
<A NAME="idx229"><!></A>
<P>An individual character from a string can be accessed or assigned using <SAMP>operator[]</SAMP>. The member function <SAMP>at()</SAMP> is almost a synonym for this operation, except that an <SAMP>out_of_range</SAMP> exception is thrown if the requested location is greater than or equal to <SAMP>size()</SAMP>.</P>
<UL><PRE>
std::cout &lt;&lt; s4[2] &lt;&lt; std::endl; // output position 2 of s4
s4[2] = 'x'; // change position 2
std::cout &lt;&lt; s4.at(2) &lt;&lt; std::endl; // output updated value
</PRE></UL>
<A NAME="idx230"><!></A>
<P>The member function<SAMP> c_str()</SAMP> returns a pointer to a null-terminated character array, whose elements are the same as those contained in the <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>. This lets you use <B><I>string</I></B>s with functions that require a pointer to a conventional C-style character array. The resulting pointer is declared as constant, which means that you cannot use <SAMP>c_str()</SAMP> to modify the string. In addition, the value returned by <SAMP>c_str()</SAMP> might not be valid after any operation that may cause reallocation, such as <SAMP>append()</SAMP> or <SAMP>insert()</SAMP>. The member function <SAMP>data()</SAMP> returns a pointer to the underlying character buffer. Note that the buffer returned by <SAMP>data()</SAMP> is not null-terminated, and must not be used with functions that expect null-terminated sequences.</P>
<UL><PRE>
char d[256];
std::strcpy(d, s4.c_str()); // copy s4 into array d
</PRE></UL>
<A NAME="1225"><H3>12.2.5 Iterators</H3></A>
<A NAME="idx231"><!></A>
<P>The member functions <SAMP>begin()</SAMP> and <SAMP>end()</SAMP> return beginning and ending random-access <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s for the string. The values denoted by the <B><I>iterator</I></B>s are individual string elements. The functions <SAMP>rbegin()</SAMP> and <SAMP>rend()</SAMP> return backwards <B><I>iterator</I></B>s.</P>
<A NAME="1226"><H3>12.2.6 Insertion, Removal, and Replacement</H3></A>
<A NAME="idx232"><!></A>
<P>The <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> member functions <SAMP>insert()</SAMP> and <SAMP>erase()</SAMP> are similar to the <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> functions <SAMP>insert()</SAMP> and <SAMP>erase()</SAMP>. Like the vector versions, they can take <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s as arguments, and specify the insertion or removal of the ranges specified by the arguments. The function <SAMP>replace()</SAMP> is a combination of erase and insert, in effect replacing the specified range with new values.</P>
<UL><PRE>
s2.insert(s2.begin()+2, aList.begin(), aList.end());
s2.erase(s2.begin()+3, s2.begin()+5);
s2.replace(s2.begin()+3, s2.begin()+6, s3.begin(), s3.end());
</PRE></UL>
<BLOCKQUOTE><HR><B>
NOTE -- Note that the contents of an iterator are not guaranteed to be valid after any operation that might force a reallocation of the internal string buffer, such as an append or an insertion.
</B><HR></BLOCKQUOTE>
<P>The functions above also have non-iterator implementations. The <SAMP>insert()</SAMP> member function takes as argument a position and a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>, and inserts the <B><I>string</I></B> into the given position. The erase function takes two integer arguments, a position and a length, and removes the characters specified. The replace function takes two similar integer arguments, as well as a string and an optional length, and replaces the indicated range with the string or with an initial portion of a string, if the length has been explicitly specified.</P>
<UL><PRE>
s3.insert(3, "abc"); // insert abc after position 3
s3.erase(4, 2); // remove positions 4 and 5
s3.replace(4, 2, "pqr"); // replace positions 4 and 5 with pqr
</PRE></UL>
<A NAME="1227"><H3>12.2.7 Copy and Substring</H3></A>
<A NAME="idx233"><!></A>
<P>The member function <SAMP>copy()</SAMP> generates a substring and copies this substring to the <SAMP>char*</SAMP> target given as the first argument. The range of values for the substring is specified by either a length, or by a length and starting position. If only a length is provided, copying begins at the start of the string:</P>
<UL><PRE>
std::string s1("0123456789");
char buf[11] = "----------";
s1.copy(buf,3,5); // copy 3 characters from s1 into buf,
// starting after position 5
// buf now contains 567-------
s1.copy(buf,5); // copy the first 5 characters of s1 into buf
// buf now contains 01234-----
</PRE></UL>
<A NAME="idx234"><!></A>
<P>The member function <SAMP>substr()</SAMP> returns a <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> that represents a portion of the current <B><I>string</I></B>. The range is specified by either an initial position, or a position and a length:</P>
<UL><PRE>
std::cout &lt;&lt; s1.substr(3) &lt;&lt; std::endl; // output 3 to end
std::cout &lt;&lt; s1.substr(3,2) &lt;&lt; std::endl; // output positions 3
// and 4
</PRE></UL>
<A NAME="idx235"><!></A>
<A NAME="1228"><H3>12.2.8 string Comparisons</H3></A>
<A NAME="idx236"><!></A>
<P>The member function <SAMP>compare()</SAMP> is used to perform a lexical comparison between the receiver and an argument string. Optional arguments permit the specification of a different starting position, or a starting position and length of the argument string. See <A HREF="13-6.html#1365">Section&nbsp;13.6.5</A> for a description of lexicographical ordering. The function returns a negative value if the receiver is lexically smaller than the argument, a zero value if they are equal, and a positive value if the receiver is larger than the argument.</P>
<P>The relational and equality operators, <SAMP>operator&lt;()</SAMP>,<SAMP> operator&lt;=()</SAMP>,<SAMP> operator==()</SAMP>,<SAMP> operator!=()</SAMP>,<SAMP> operator&gt;=()</SAMP>, and <SAMP>operator&gt;()</SAMP>, are all defined using the comparison member function. Comparisons can be made either between two strings, or between strings and ordinary C-style character literals.</P>
<P>Having explained the functionality of <SAMP>compare()</SAMP>, we should note that users seldom invoke this member function directly. Instead, comparisons of strings are usually performed using the conventional comparison operators, which in turn make use of the function <SAMP>compare()</SAMP>.</P>
<A NAME="idx237"><!></A>
<A NAME="1229"><H3>12.2.9 Searching Operations</H3></A>
<A NAME="idx238"><!></A>
<P>The member function <SAMP>find()</SAMP> determines the first occurrence of the argument string in the current string. An optional integer argument lets you specify the starting position for the search. (Remember that string index positions begin at zero.) If the function can locate such a match, it returns the starting index of the match in the current string. Otherwise, it returns a value out of the range of the set of legal subscripts for the string. The function <SAMP>rfind()</SAMP> is similar, but scans the string from the end, moving backwards.</P>
<UL><PRE>
s1 = "mississippi";
std::cout &lt;&lt; s1.find("ss") &lt;&lt; std::endl; // returns 2
std::cout &lt;&lt; s1.find("ss", 3) &lt;&lt; std::endl; // returns 5
std::cout &lt;&lt; s1.rfind("ss") &lt;&lt; std::endl; // returns 5
std::cout &lt;&lt; s1.rfind("ss", 4) &lt;&lt; std::endl;// returns 2
</PRE></UL>
<A NAME="idx239"><!></A>
<P>The functions <SAMP>find_first_of()</SAMP>, <SAMP>find_last_of()</SAMP>, <SAMP>find_first_not_of()</SAMP>, and <SAMP>find_last_not_of()</SAMP> treat the argument string as a set of characters. As with many of the other functions, one or two optional integer arguments can be used to specify a subset of the current string. These functions find the first or last character that is either present or absent from the argument set. The position of the given character, if located, is returned. If no such character exists, a value out of the range of any legal subscript is returned.</P>
<UL><PRE>
i = s2.find_first_of("aeiou"); // find first vowel
j = s2.find_first_not_of("aeiou", i); // next non-vowel
</PRE></UL>
<BR>
<HR>
<A HREF="12-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="12-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,69 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Example Function: Split a Line into Words</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="12-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="IV.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>12.3 Example Function: Split a Line into Words</H2>
<A NAME="idx240"><!></A>
<A NAME="idx241"><!></A>
<P>In this section we illustrate the use of some of the <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> functions by defining a function to split a line of text into individual words. We have already made use of this function in the concordance example program in <A HREF="9-3.html#933">Section&nbsp;9.3.3</A>.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The split function is in the concordance program in file concord.cpp.
</B><HR></BLOCKQUOTE>
<P>There are three arguments to this function. The first two are <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>s, describing the line of text and the separators to be used to differentiate words, respectively. The third argument is a <B><I><A HREF="../stdlibref/list.html">list</A></I></B> of <B><I>string</I></B>s, used to return the individual words in the line.</P>
<UL><PRE>
void split (const std::string&amp; text, const std::string&amp; separators,
std::list&lt;std::string,
std::allocator&lt;std::string&gt; &gt;&amp; words) {
size_t n = text.length ();
size_t start = text.find_first_not_of (separators);
while (start &lt; n) {
size_t stop = text.find_first_of (separators, start);
if (stop &gt; n) stop = n;
words.push_back (text.substr (start, stop-start));
start = text.find_first_not_of (separators, stop+1);
}
}
</PRE></UL>
<P>The program begins by finding <SAMP>start</SAMP>, the index of the first character that is <I>not</I> a separator. The loop then looks for <SAMP>stop</SAMP>, the index of the next character that <I>is</I> a separator, or uses the end of the string if no such value is found. These two indexes delimit a word, which is copied out of the text using a substring operation and inserted into the <B><I><A HREF="../stdlibref/list.html">list</A></I></B> of words. A search is then made to discover the start of the next word, and the loop continues. When the index value exceeds the limits of the <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>, execution stops.</P>
<BR>
<HR>
<A HREF="12-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="IV.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,59 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>string</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="11-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="12-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 12: string</H1>
<UL>
<UL><LI><A HREF="12-1.html">12.1 The string Abstraction</A></LI></UL>
<UL><UL><LI><A HREF="12-1.html#1211">12.1.1 Include Files</A></LI></UL></UL>
<UL><LI><A HREF="12-2.html">12.2 string Operations</A></LI></UL>
<UL><UL><LI><A HREF="12-2.html#1221">12.2.1 Declaration and Initialization of string</A></LI></UL></UL>
<UL><UL><LI><A HREF="12-2.html#1222">12.2.2 Resetting Size and Capacity</A></LI></UL></UL>
<UL><UL><LI><A HREF="12-2.html#1223">12.2.3 Assignment, Append, and Swap</A></LI></UL></UL>
<UL><UL><LI><A HREF="12-2.html#1224">12.2.4 Character Access</A></LI></UL></UL>
<UL><UL><LI><A HREF="12-2.html#1225">12.2.5 Iterators</A></LI></UL></UL>
<UL><UL><LI><A HREF="12-2.html#1226">12.2.6 Insertion, Removal, and Replacement</A></LI></UL></UL>
<UL><UL><LI><A HREF="12-2.html#1227">12.2.7 Copy and Substring</A></LI></UL></UL>
<UL><UL><LI><A HREF="12-2.html#1228">12.2.8 string Comparisons</A></LI></UL></UL>
<UL><UL><LI><A HREF="12-2.html#1229">12.2.9 Searching Operations</A></LI></UL></UL>
<UL><LI><A HREF="12-3.html">12.3 Example Function: Split a Line into Words</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="11-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="12-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,203 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>13.1 Overview</H2>
<A NAME="idx242"><!></A>
<P>In this chapter and in <A HREF="14.html">Chapter&nbsp;14</A> we examine and illustrate each of the generic algorithms provided by the C++ Standard Library. The names and a short description of each of the algorithms in this chapter are given in <A HREF="13-1.html#Table&nbsp;19">Table&nbsp;19</A>. We have divided the algorithms into several categories, based on how they are typically used. This division differs from the categories used in the C++ Standard Library definition, which is based upon whether or not the algorithms modify their arguments.</P>
<H4><A NAME="Table&nbsp;19">Table&nbsp;19: Generic algorithms of the C++ Standard Library&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Algorithm</B>
</td><td valign=top><B>Purpose</B>
</td></tr>
<A NAME="idx243"><!></A>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Algorithms initializing a sequence</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>copy()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Copies a sequence into another sequence</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>copy_backward()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Copies a sequence into another sequence</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>fill()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Fills a sequence with an initial value</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>fill_n()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Fills n positions with an initial value</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>generate()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Initializes a sequence using a generator</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>generate_n()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Initializes n positions using a generator </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>swap()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Exchanges values</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>swap_ranges()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Swaps values from two parallel sequences </P>
</td></tr>
<A NAME="idx244"><!></A>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Searching algorithms</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>adjacent_find()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Finds consecutive duplicate elements </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>find()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Finds an element matching the argument </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>find_end()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Finds the last occurrence of a sub-sequence in a sequence</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>find_first_of()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Finds the first occurrence of one member of a sequence in another sequence</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>find_if()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Finds an element satisfying a condition </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>max_element()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Finds the maximum value in a sequence </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>min_element()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Finds the minimum value in a sequence </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>mismatch()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Finds first mismatch in parallel sequences</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>search()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Matches a sub-sequence within a sequence </P>
</td></tr>
<A NAME="idx245"><!></A>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Algorithms for in-place transformations</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>inplace_merge()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Merges two adjacent sequences into one </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>next_permutation()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Generates permutations in sequence </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>partition()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Partitions elements into two groups </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>permutation()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Generates successive permutations of a sequence based on an ordering function</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>prev_permutation()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Generates permutations in reverse sequence </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>random_shuffle()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Randomly rearranges elements in a sequence</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>replace()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Replaces specific values with new value </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>replace_if()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Replaces elements matching predicate</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>reverse()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Reverses the elements in a sequence </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>rotate()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Rotates elements in a sequence around a point </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>stable_partition()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Partitions preserving original ordering </P>
</td></tr>
<A NAME="idx246"><!></A>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Removal algorithms </I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>remove()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Removes elements that match condition</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>unique()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Removes all but first of duplicate values in sequences</P>
</td></tr>
<A NAME="idx247"><!></A>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Scalar-producing algorithms</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>accumulate()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Reduces sequence to a scalar value </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>count()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Counts number of elements matching value </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>count_if()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Counts elements matching predicate</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>equal()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Checks two sequences for equality </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>inner_product()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Gives inner product of two parallel sequences</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>lexicographical_compare()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Compares two sequences</P>
</td></tr>
<A NAME="idx248"><!></A>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Sequence-generating algorithms</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>adjacent_difference()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Generates sequence of adjacent differences</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>partial_sum()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Generates sequence of partial sums </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>transform()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Transforms each element</P>
</td></tr>
<A NAME="idx249"><!></A>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"> <B><I>Miscellaneous operations </I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>for_each()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Applies a function to each element of a collection </P>
</td></tr>
</TABLE>
<P>In this chapter, we illustrate the use of each algorithm with a series of short examples. Many of the algorithms are also used in the sample programs provided in the chapters on the various container classes. These cross references have been noted where appropriate.</P>
<A NAME="idx250"><!></A>
<P>All the short example programs described in this section are contained in a number of files, named <SAMP>alg1.cpp</SAMP> through <SAMP>alg6.cpp</SAMP>. In the files, the example programs are augmented with output statements describing the test programs and illustrating the results of executing the algorithms. So as not to confuse the reader with unnecessary detail, we have generally omitted these output statements from the descriptions here. If you wish to see the test programs complete with output statements, you can compile and execute the test files. The expected output from these programs is also included in the distribution.</P>
<A NAME="1311"><H3>13.1.1 Include Files</H3></A>
<A NAME="idx251"><!></A>
<P>To use any of the generic algorithms, you must first include the appropriate header file. The majority of the functions are defined in the header file <SAMP>algorithm</SAMP>. The functions <SAMP>std::accumulate()</SAMP>, <SAMP>std::inner_product()</SAMP>, <SAMP>std::partial_sum()</SAMP>, and <SAMP>std::adjacent_difference()</SAMP> are defined in the header file <SAMP>numeric</SAMP>.</P>
<UL><PRE>
#include &lt;algorithm&gt;
#include &lt;numeric&gt;
</PRE></UL>
<BR>
<HR>
<A HREF="13.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,286 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Initialization Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>13.2 Initialization Algorithms</H2>
<A NAME="idx252"><!></A>
<A NAME="idx253"><!></A>
<P>The first set of algorithms we cover are used chiefly, although not exclusively, to initialize a newly created sequence with certain values. The C++ Standard Library provides several initialization algorithms. The initialization algorithms all overwrite every element in a container. The difference between the algorithms is the source for the values used in initialization. The <SAMP>std::fill()</SAMP> algorithm repeats a single value, the <SAMP>std::copy()</SAMP> algorithm reads values from a second container, and the <SAMP>std::generate()</SAMP> algorithm invokes a function for each new value. In our discussion we provide examples of how to apply these algorithms, and suggest how to choose one algorithm over another.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The sample programs described in the following sections are in the file alg1.cpp. We generally omit output statements from the descriptions of the programs provided here, although they are included in the compete versions.
</B><HR></BLOCKQUOTE>
<A NAME="1321"><H3>13.2.1 Fill a Sequence with An Initial Value</H3></A>
<A NAME="idx254"><!></A>
<P>The <SAMP>std::fill()</SAMP> and <SAMP>std::fill_n()</SAMP> algorithms are used to initialize or reinitialize a sequence with a fixed value. Their declarations are as follows:</P>
<UL><PRE>
namespace std {
void fill(ForwardIterator first,
ForwardIterator last, const T&amp;);
void fill_n(OutputIterator, Size, const T&amp;);
}
</PRE></UL>
<A NAME="idx255"><!></A>
<P>The example program illustrates several uses of the algorithm:</P>
<A NAME="idx259"><!></A>
<A NAME="idx258"><!></A>
<A NAME="idx257"><!></A>
<A NAME="idx256"><!></A>
<UL><PRE>
void fill_example ()
// illustrates the use of the fill algorithm
// see alg1.cpp for complete source code
{
// example 1, fill an array with initial values
char buffer[100], *bufferp = buffer;
std::fill(bufferp, bufferp + 100, '\0');
std::fill_n(bufferp, 10, 'x');
// example 2, use fill_n to initialize a list
std::list&lt;string&gt; aList(5, "nothing");
std::fill_n(inserter(aList, aList.begin()), 10, "empty");
// example 3, use fill to overwrite values in list
std::fill(aList.begin(), aList.end(), "full");
// example 4, fill in a portion of a collection
std::vector&lt;int&gt; iVec(10);
std::generate(iVec.begin(), iVec.end(), iotaGen(1));
std::vector&lt;int&gt;::iterator&amp; seven =
std::find(iVec.begin(), iVec.end(), 7);
std::fill(iVec.begin(), seven, 0);
}
</PRE></UL>
<P>In example 1, an array of character values is declared. The <SAMP>std::fill()</SAMP> algorithm is invoked to initialize each location in this array with a null character value. The first 10 positions are then replaced with the character <SAMP>'x'</SAMP> by using the algorithm <SAMP>std::fill_n()</SAMP>. Note that the <SAMP>std::fill()</SAMP> algorithm requires both starting and past-end <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s as arguments, whereas the <SAMP>std::fill_n()</SAMP> algorithm uses a starting <B><I>iterator</I></B> and a count.</P>
<A NAME="idx260"><!></A>
<P>By applying an <I>insert iterator</I> (<A HREF="2-4.html">Section&nbsp;2.4</A>), example 2 illustrates how the <SAMP>std::fill_n()</SAMP> algorithm can be used to initialize a variable length container, such as a <B><I><A HREF="../stdlibref/list.html">list</A></I></B>. In this case the <B><I>list</I></B> initially contains five elements, all holding the text <SAMP>"nothing"</SAMP>. The call on <SAMP>std::fill_n()</SAMP> then inserts ten instances of the string <SAMP>"empty"</SAMP>. The resulting <B><I>list</I></B> contains fifteen elements.</P>
<P>Examples 3 and 4 illustrate how <SAMP>std::fill()</SAMP> can be used to change the values in an existing container. In example 3 each of the fifteen elements in the <B><I><A HREF="../stdlibref/list.html">list</A></I></B> created in example 2 is replaced by the string <SAMP>"full"</SAMP>. </P>
<P>Example 4 overwrites only a portion of a <B><I><A HREF="../stdlibref/list.html">list</A></I></B>. Using the generic algorithm <SAMP>std::generate()</SAMP> and the function object <B><I>iotaGen</I></B> (see <A HREF="3-2.html">Section&nbsp;3.2</A> and <A HREF="13-2.html#1323">Section&nbsp;13.2.3</A>), a vector is initialized to the values <SAMP>1 2 3... 10</SAMP>. The <SAMP>std::find()</SAMP> algorithm (see <A HREF="13-3.html#1331">Section&nbsp;13.3.1</A>) is used to locate the position of the element 7, saving the location in an iterator appropriate for the <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> datatype. The<SAMP> std::fill()</SAMP> call then replaces all values up to, but not including, the <SAMP>7</SAMP> entry with the value <SAMP>0</SAMP>. The resulting vector has six zero fields, followed by the values <SAMP>7</SAMP>, <SAMP>8</SAMP>, <SAMP>9</SAMP> and <SAMP>10</SAMP>.</P>
<P>The <SAMP>std::fill()</SAMP> and<SAMP> std::fill_n()</SAMP> algorithm can be used with all the container classes contained in the C++ Standard Library, although insert iterators must be used with ordered containers, such as <B><I><A HREF="../stdlibref/set.html">set</A></I></B>s.</P>
<A NAME="1322"><H3>13.2.2 Copy One Sequence Into Another Sequence</H3></A>
<A NAME="idx261"><!></A>
<P>The algorithms <SAMP>std::copy()</SAMP> and <SAMP>std::copy_backward()</SAMP> are versatile functions that can be used for a number of different purposes, and are probably the most commonly executed algorithms in the C++ Standard Library. The declarations for these algorithms are as follows:</P>
<UL><PRE>
namespace std {
OutputIterator copy (InputIterator first, InputIterator last,
OutputIterator result);
BidirectionalIterator copy_backward
(BidirectionalIterator first, BidirectionalIterator last,
BidirectionalIterator result);
}
</PRE></UL>
<A NAME="idx262"><!></A>
<P>The result returned by the <SAMP>copy()</SAMP> function is a pointer to the end of the copied sequence. However, the result of one <SAMP>copy()</SAMP> operation can be used as a starting iterator in a subsequent <SAMP>copy()</SAMP> to make a <I>catenation</I> of values.</P>
<P>Uses of the copy algorithm include:</P>
<UL>
<LI><P CLASS="LIST">Duplicating an entire sequence by copying into a new sequence</P></LI>
<LI><P CLASS="LIST">Creating sub-sequences of an existing sequence</P></LI>
<LI><P CLASS="LIST">Adding elements into a sequence</P></LI>
<LI><P CLASS="LIST">Copying a sequence from input or to output</P></LI>
<LI><P CLASS="LIST">Converting a sequence from one form into another</P></LI>
</UL>
<A NAME="idx263"><!></A>
<P>The uses of the copy algorithm are illustrated in the following sample program:</P>
<A NAME="idx268"><!></A>
<A NAME="idx267"><!></A>
<A NAME="idx266"><!></A>
<A NAME="idx265"><!></A>
<A NAME="idx264"><!></A>
<UL><PRE>
void copy_example()
// illustrates the use of the copy algorithm
// see alg1.cpp for complete source code
{
char *source = "reprise";
char *surpass = "surpass";
char buffer[120], *bufferp = buffer;
// example 1, a simple copy
std::copy(source, source + strlen(source) + 1, bufferp);
// example 2, self copies
std::copy(bufferp + 2, bufferp + strlen(buffer) + 1, bufferp);
int buflen = strlen(buffer) + 1;
std::copy_backward(bufferp, bufferp + buflen,
bufferp + buflen + 3);
std::copy(surpass, surpass + 3, bufferp);
// example 3, copy to output
std::copy(bufferp, bufferp + strlen(buffer),
std::ostream_iterator&lt;char,char&gt;(std::cout));
std::cout &lt;&lt; std::endl;
// example 4, use copy to convert type
std::list&lt;char&gt; char_list;
std::copy (bufferp, bufferp + strlen(buffer),
std::inserter(char_list, char_list.end()));
char *big = "big ";
std::copy(big, big + 4,
std::inserter(char_list, char_list.begin()));
char buffer2[120], *buffer2p = buffer2;
*std::copy(char_list.begin(), char_list.end(), buffer2p) = '\0';
std::cout &lt;&lt; buffer2 &lt;&lt; std::endl;
}
</PRE></UL>
<P>In example 1, the first call on <SAMP>std::copy()</SAMP> simply copies the string pointed to by the variable <SAMP>source</SAMP> into a buffer, resulting in the buffer containing the text <SAMP>"reprise"</SAMP>. Note that the ending position for the copy is one past the terminating null character, thus ensuring the null character is included in the copy operation.</P>
<P>The <SAMP>std::copy()</SAMP> operation is specifically designed to permit <I>self-copies</I>, which are copies of a sequence onto itself, as long as the destination <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> does not fall within the range formed by the source <B><I>iterator</I></B>s. This is illustrated by example 2. Here the copy begins at position 2 of the buffer and extends to the end, copying characters into the beginning of the buffer. This results in the buffer holding the value <SAMP>"prise"</SAMP>. </P>
<P>The second half of example 2 illustrates the use of the <SAMP>std::copy_backward()</SAMP> algorithm. This function performs the same task as the <SAMP>std::copy()</SAMP> algorithm, but moves elements from the end of the sequence first, progressing to the front of the sequence. If you think of the argument as a string, characters are moved starting from the right and progressing to the left. In this case the result is that <SAMP>buffer</SAMP> is assigned the value <SAMP>"priprise"</SAMP>. The first three characters are then modified by another <SAMP>std::copy()</SAMP> operation to the values <SAMP>"sur"</SAMP>, resulting in <SAMP>buffer</SAMP> holding the value<SAMP> "surprise"</SAMP>.</P>
<BLOCKQUOTE><HR><B>
NOTE -- In the copy_backwards algorithm, note that it is the order of transfer that is backwards, not the elements themselves; the relative placement of moved values in the target is the same as in the source.
</B><HR></BLOCKQUOTE>
<P>Example 3 illustrates <SAMP>std::copy()</SAMP> being used to move values to an output stream (see <A HREF="2-3.html#232">Section&nbsp;2.3.2</A>). The target in this case is an <SAMP>ostream_iterator</SAMP> generated for the output stream <SAMP>std::cout</SAMP>. A similar mechanism can be used for input values. For example, a simple mechanism to copy every word in the input stream into a <B><I><A HREF="../stdlibref/list.html">list</A></I></B> is the following call on <SAMP>copy()</SAMP>:</P>
<UL><PRE>
std::list&lt;std::string&gt; words;
std::istream_iterator&lt;std::string, char&gt; in_stream(std::cin), eof;
std::copy(in_stream, eof, std::inserter(words,
words.begin()));
</PRE></UL>
<P>This technique is used in the spell checking program described in <A HREF="8-3.html">Section&nbsp;8.3</A>.</P>
<A NAME="idx269"><!></A>
<P>Copy can also be used to convert from one type of stream to another. For example, the call in example 4 of the sample program copies the characters held in the buffer one by one into a <B><I><A HREF="../stdlibref/list.html">list</A></I></B> of characters. The call on <SAMP>std::inserter()</SAMP> creates an insert iterator, used to insert values into the <B><I>list</I></B>. The first call on <SAMP>std::copy()</SAMP> places the string <SAMP>surprise</SAMP>, created in example 2, into the <B><I>list</I></B>. The second call on <SAMP>std::copy()</SAMP> inserts the values from the string <SAMP>"big "</SAMP> onto the front of the <B><I>list</I></B>, resulting in the <B><I>list</I></B> containing the characters <SAMP>big surprise</SAMP>. The final call on <SAMP>std::copy()</SAMP> illustrates the reverse process, copying characters from a <B><I>list</I></B> back into a character buffer.</P>
<A NAME="1323"><H3>13.2.3 Initialize a Sequence with Generated Values</H3></A>
<A NAME="idx270"><!></A>
<P>A <I>generator</I> is a function that returns a series of values on successive invocations. Probably the generator you are most familiar with is a random number generator. However, generators can be constructed for a variety of different purposes, including initializing sequences.</P>
<A NAME="idx271"><!></A>
<P>Like <SAMP>std::fill()</SAMP> and <SAMP>std::fill_n()</SAMP>, the algorithms <SAMP>std::generate()</SAMP> and <SAMP>std::generate_n()</SAMP> are used to initialize or reinitialize a sequence. However, instead of a fixed argument, these algorithms draw their values from a generator. The declarations of these algorithms are as follows:</P>
<UL><PRE>
namespace std {
void generate(ForwardIterator, ForwardIterator, Generator);
void generate_n(OutputIterator, Size, Generator);
}
</PRE></UL>
<A NAME="idx272"><!></A>
<P>Our example program shows several uses of the generate algorithm to initialize a sequence:</P>
<A NAME="idx274"><!></A>
<A NAME="idx273"><!></A>
<UL><PRE>
string generateLabel () {
// generate a unique label string of the form L_ddd
// see alg1.cpp for complete source code
static int lastLabel = 0;
char labelBuffer[80];
std::ostrstream ost(labelBuffer, 80);
ost &lt;&lt; "L_" &lt;&lt; lastLabel++ &lt;&lt; '\0';
return std::string(labelBuffer);
}
void generate_example ()
// illustrate the use of the generate and generate_n algorithms
{
// example 1, generate a list of label values
std::list&lt;std::string&gt; labelList;
std::generate_n(std::inserter(labelList, labelList.begin()),
4, generateLabel);
// example 2, generate an arithmetic progression
std::vector&lt;int&gt; iVec(10);
std::generate(iVec.begin(), iVec.end(), iotaGen(2));
std::generate_n(iVec.begin(), 5, iotaGen(7));
}
}
</PRE></UL>
<A NAME="idx275"><!></A>
<P>A generator can be constructed as a simple function that <I>remembers</I> information about its previous history in one or more static variables. An example is shown in the beginning of the example program, where the function <SAMP>generateLabel()</SAMP> is described. This function creates a sequence of unique string labels, such as might be needed by a compiler. Each invocation on the function <SAMP>generateLabel()</SAMP> results in a new string of the form <SAMP>L_ddd</SAMP>, each with a unique digit value. Because the variable named <SAMP>lastLabel</SAMP> is declared as <SAMP>static</SAMP>, its value is remembered from one invocation to the next. The first example of the sample illustrates how this function might be used in combination with the <SAMP>std::generate_n()</SAMP> algorithm to initialize a list of four label values.</P>
<A NAME="idx276"><!></A>
<P>As we described in <A HREF="3.html">Chapter&nbsp;3</A>, a function is any object that will respond to the function call operator. Using this definition, classes can easily be constructed as functions. The class <B><I>iotaGen</I></B><I>,</I> is an example (see <A HREF="3-2.html">Section&nbsp;3.2</A>). The <B><I>iotaGen</I></B> function object creates a generator for an integer arithmetic sequence. In the second example in the sample program, this sequence is used to initialize a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> with the integer values 2 through 11. A call on <SAMP>std::generate_n()</SAMP> is then used to overwrite the first 5 positions of the <B><I>vector</I></B> with the values 7 through 11, resulting in the <B><I>vector</I></B> <SAMP>7 8 9 10 11 7 8 9 10 11</SAMP>.</P>
<A NAME="1324"><H3>13.2.4 Swap Values from Two Parallel Ranges</H3></A>
<A NAME="idx277"><!></A>
<P>The template function <SAMP>std::swap()</SAMP> can be used to exchange the values of two objects of the same type. It has the following definition:</P>
<UL><PRE>
namespace std {
template &lt;class T&gt; void swap (T&amp; a, T&amp; b)
{
T temp(a);
a = b;
b = temp;
}
}
</PRE></UL>
<A NAME="idx278"><!></A>
<P>The function is generalized to <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s in the function named <SAMP>std::iter_swap().</SAMP> The algorithm <SAMP>std::swap_ranges()</SAMP> extends this to entire sequences. The values denoted by the first sequence are exchanged with the values denoted by a second, parallel sequence. The description of the <SAMP>std::swap_ranges()</SAMP> algorithm is as follows:</P>
<UL><PRE>
namespace std {
ForwardIterator swap_ranges
(ForwardIterator first, ForwardIterator last,
ForwardIterator first2);
}
</PRE></UL>
<P>The second range is described only by a starting <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>. It is assumed but not verified that the second range has at least as many elements as the first range. </P>
<BLOCKQUOTE><HR><B>
NOTE -- A number of algorithms operate on two parallel sequences. In most cases, the second sequence is identified using only a starting iterator, not a starting and ending iterator pair. It is assumed, but never verified, that the second sequence is at least as large as the first. Errors will occur if this condition is not satisfied.
</B><HR></BLOCKQUOTE>
<P>In the example program, both <SAMP>std::swap()</SAMP> and <SAMP>std::iter_swap()</SAMP> are used separately and in combination:</P>
<A NAME="idx279"><!></A>
<UL><PRE>
void swap_example ()
// illustrates the use of the algorithm swap_ranges
// see alg1.cpp for complete source code
{
// first make two parallel sequences
int data[] = {12, 27, 14, 64}, *datap = data;
std::vector&lt;int&gt; aVec(4);
std::generate(aVec.begin(), aVec.end(), iotaGen(1));
// illustrate swap and iter_swap
std::swap(data[0], data[2]);
std::vector&lt;int&gt;::iterator last = aVec.end();
last--;
std::iter_swap(aVec.begin(), last);
// now swap the entire sequence
std::swap_ranges(aVec.begin(), aVec.end(), datap);
}
</PRE></UL>
<BR>
<HR>
<A HREF="13-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,369 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Searching Operations</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>13.3 Searching Operations</H2>
<A NAME="idx280"><!></A>
<P>The next category of algorithms we describe are used to locate elements within a sequence that satisfy certain properties. Most commonly the result of a search is then used as an argument to a further operation, for example, <SAMP>std::copy()</SAMP> (<A HREF="13-2.html#1322">Section&nbsp;13.2.2</A>), <SAMP>std::partition()</SAMP> (<A HREF="13-4.html#1344">Section&nbsp;13.4.4</A>), or <SAMP>std::inplace_merge()</SAMP> (<A HREF="13-4.html#1346">Section&nbsp;13.4.6</A>.)</P>
<BLOCKQUOTE><HR><B>
NOTE -- The example functions described in the following sections are in the file alg2.cpp.
</B><HR></BLOCKQUOTE>
<P>The searching routines described in this section return an iterator that identifies the first element that satisfies the search condition. It is common to store this value in an <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> variable, as follows:</P>
<UL><PRE>
std::list&lt;int&gt;::iterator where;
where = std::find(aList.begin(), aList.end(), 7);
</PRE></UL>
<P>If you want to locate <I>all</I> the elements that satisfy the search conditions, you must write a loop. In that loop, the value yielded by a previous search is first advanced, since otherwise the value yielded by the previous search would once again be returned. The resulting value is then used as a starting point for the new search. For example, the following loop from the <SAMP>std::adjacent_find()</SAMP> example program (<A HREF="13-3.html#1332">Section&nbsp;13.3.2</A>) will print the value of all repeated characters in a string argument:</P>
<UL><PRE>
while ((where = std::adjacent_find(where, stop)) != stop) {
std::cout &lt;&lt; "double " &lt;&lt; *where &lt;&lt; " in position "
&lt;&lt; where - start &lt;&lt; std::endl;
++where;
}
</PRE></UL>
<BLOCKQUOTE><HR><B>
NOTE -- The searching algorithms in the C++ Standard Library all return the end-of-sequence iterator if no value is found that matches the search condition. As it is generally illegal to dereference the end-of-sequence value, it is important to check for this condition before proceeding to use the result of a search.
</B><HR></BLOCKQUOTE>
<P>Many of the searching algorithms have an optional argument that can specify a function for comparing elements in place of the equality <SAMP>operator==()</SAMP> for the container element type. In the descriptions of the algorithms, we write these optional arguments inside square brackets to indicate they need not be specified if the standard equality operator is acceptable.</P>
<A NAME="1331"><H3>13.3.1 Find an Element Satisfying a Condition</H3></A>
<A NAME="idx281"><!></A>
<P>There are two algorithms, <SAMP>std::find()</SAMP> and <SAMP>std::find_if()</SAMP>, that are used to find the first element that satisfies a condition. The declarations of these two algorithms are as follows:</P>
<UL><PRE>
namespace std {
InputIterator find_if(InputIterator first,
InputIterator last, Predicate);
InputIterator find(InputIterator first,
InputIterator last, const T&amp;);
}
</PRE></UL>
<P>The algorithm <SAMP>std::find_if()</SAMP> takes as argument a predicate function, which can be any function that returns a boolean value (see <A HREF="3-3.html">Section&nbsp;3.3</A>). <SAMP>std::find_if()</SAMP> returns a new <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> that designates the first element in the sequence that satisfies the predicate. The second argument, the past-the-end iterator, is returned if no element is found that matches the requirement. Because the resulting value is an <B><I>iterator</I></B>, the dereference operator <SAMP>*</SAMP> must be used to obtain the matching value. This is illustrated in the example program.</P>
<P>The second form of the algorithm, <SAMP>std::find()</SAMP>, replaces the predicate function with a specific value, and returns the first element in the sequence that tests equal to this value, using <SAMP>operator==()</SAMP> for the given datatype.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The algorithms find() and find_if() perform a linear sequential search through the associated structures. The set and map data structures, which are ordered, provide their own find() member functions, which are more efficient. Because of this, the generic find() algorithm should not be used with set and map.
</B><HR></BLOCKQUOTE>
<P>The following example program illustrates the use of <SAMP>std::find()</SAMP> and <SAMP>std::find_if()</SAMP>:</P>
<A NAME="idx282"><!></A>
<UL><PRE>
void find_test ()
// illustrates the use of the find algorithm
// see alg2.cpp for complete source code
{
int vintageYears[] = {1967, 1972, 1974, 1980, 1995};
int *start = vintageYears;
int *stop = start + 5;
int *where = std::find_if(start, stop, isLeapYear);
if (where != stop)
std::cout &lt;&lt; "first vintage leap year is "
&lt;&lt; *where &lt;&lt; std::endl;
else
std::cout &lt;&lt; "no vintage leap years" &lt;&lt; std::endl;
where = std::find(start, stop, 1995);
if (where != stop)
std::cout &lt;&lt; "1995 is position " &lt;&lt; where - start
&lt;&lt; " in sequence" &lt;&lt; std::endl;
else
std::cout &lt;&lt; "1995 does not occur in sequence" &lt;&lt; std::endl;
}
</PRE></UL>
<A NAME="1332"><H3>13.3.2 Find Consecutive Duplicate Elements</H3></A>
<A NAME="idx283"><!></A>
<P>The <SAMP>std::adjacent_find()</SAMP> algorithm is used to discover the first element in a sequence equal to the next immediately following element. For example, if a sequence contained the values<SAMP> 1 4 2 5 6 6 7 5</SAMP>, the algorithm would return an <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> corresponding to the first <SAMP>6</SAMP> value. If no value satisfying the condition is found, then the end-of-sequence iterator is returned. The declaration of the algorithm is as follows:</P>
<UL><PRE>
namespace std {
ForwardIterator adjacent_find (ForwardIterator first,
ForwardIterator last
[, BinaryPredicate ] );
}
</PRE></UL>
<P>The first two arguments specify the sequence to be examined. The optional third argument must be a <I>binary predicate</I>, a binary function returning a boolean value. If present, the binary function is used to test adjacent elements, otherwise the equality operator, <SAMP>operator==(),</SAMP> is used.</P>
<P>The example program searches a text string for adjacent letters. In the example text these are found in positions <SAMP>5</SAMP>, <SAMP>7</SAMP>, <SAMP>9</SAMP>, <SAMP>21</SAMP>, and <SAMP>37</SAMP>. The increment is necessary inside the loop in order to avoid the same position being discovered repeatedly.</P>
<A NAME="idx284"><!></A>
<UL><PRE>
void adjacent_find_example ()
// illustrates the use of the adjacent_find instruction
// see alg2.cpp for complete source code
{
char *text = "The bookkeeper carefully opened the door.";
char *start = text;
char *stop = text + strlen(text);
char *where = start;
std::cout &lt;&lt; "In the text: " &lt;&lt; text &lt;&lt; std::endl;
while ((where = std::adjacent_find(where, stop)) != stop) {
std::cout &lt;&lt; "double " &lt;&lt; *where
&lt;&lt; " in position " &lt;&lt; where - start &lt;&lt; std::endl;
++where;
}
}
</PRE></UL>
<A NAME="1333"><H3>13.3.3 Find the First Occurrence of Any Value from a Sequence</H3></A>
<A NAME="idx285"><!></A>
<P>The algorithm <SAMP>std::find_first_of()</SAMP> is used to find the first occurrence of some element from one sequence that is also contained in another sequence: </P>
<UL><PRE>
namespace std {
ForwardIterator1 find_first_of
(ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2
[, BinaryPredicate pred ] );
}
</PRE></UL>
<P>The algorithm returns a new <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> that designates the first element found in <SAMP>[first1,last1)</SAMP> that is also contained in <SAMP>[first2,last2)</SAMP>. If no match is found, the second argument is returned. Because the resulting value is an <B><I>iterator</I></B>, the dereference operator <SAMP>*</SAMP> must be used to obtain the matching value. This is illustrated in the example program:</P>
<A NAME="idx286"><!></A>
<UL><PRE>
void find_test ()
// illustrates the use of the find algorithm
// see alg2.cpp for complete source code
{
int vintageYears[] = {1967, 1972, 1974, 1980, 1995};
int requestedYears[] = {1923, 1970, 1980, 1974 };
int *start = vintageYears;
int *stop = start + 5;
int *where = find_first_of(start, stop, requestedyears,
requestedyears+4);
if (where != stop)
std::cout &lt;&lt; "first requested vintage year is "
&lt;&lt; *where &lt;&lt; std::endl;
else
std::cout &lt;&lt; "no requested vintage years" &lt;&lt; std::endl;
}
// The output would indicate 1974.
</PRE></UL>
<P>Note that this algorithm, unlike many that manipulate two sequences, uses a starting and ending <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> pair for both sequences, not just the first sequence.</P>
<P>Like the algorithms <SAMP>std::equal()</SAMP> and <SAMP>std::mismatch()</SAMP>, an alternative version of <SAMP>std::find_first_of()</SAMP> takes an optional binary predicate that is used to compare elements from the two sequences. </P>
<P>The <B><I><A HREF="../stdlibref/basic-string.html">basic_string</A></I></B> class provides its own versions of the <SAMP>find_first_of</SAMP> and <SAMP>find_end</SAMP> algorithms, including several convenience overloads of the basic pattern indicated here.</P>
<A NAME="1334"><H3>13.3.4 Find a Sub-Sequence within a Sequence</H3></A>
<A NAME="idx287"><!></A>
<P>The algorithms <SAMP>std::search()</SAMP> and <SAMP>std::search_n()</SAMP> are used to locate the beginning of a particular sub-sequence within a larger sequence. The easiest example to understand is the problem of looking for a particular substring within a larger string, although the algorithm can be generalized to other uses. The arguments are assumed to have at least the capabilities of forward iterators.</P>
<UL><PRE>
namespace std {
ForwardIterator search
(ForwardIterator first1, ForwardIterator last1,
ForwardIterator first2, ForwardIterator last2
[, BinaryPredicate ]);
}
</PRE></UL>
<P>Suppose, for example, that we want to discover the location of the string <SAMP>"ration"</SAMP> in the string <SAMP>"dreams and aspirations"</SAMP>. The solution to this problem is shown in the example program. If no appropriate match is found, the value returned is the past-the-end iterator for the first sequence.</P>
<A NAME="idx288"><!></A>
<UL><PRE>
void search_example ()
// illustrate the use of the search algorithm
// see alg2.cpp for complete source code
{
char *base = "dreams and aspirations";
char *text = "ration";
char *where = std::search(base, base + std::strlen(base),
text, text + std::strlen(text));
if (*where != '\0')
std::cout &lt;&lt; "substring position: "
&lt;&lt; where - base &lt;&lt; std::endl;
else
std::cout &lt;&lt; "substring does not occur in text" &lt;&lt; std::endl;
}
</PRE></UL>
<P>Note that this algorithm, unlike many that manipulate two sequences, uses a starting and ending <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> pair for both sequences, not just the first sequence.</P>
<P>Like the algorithms <SAMP>std::equal()</SAMP> and <SAMP>std::mismatch()</SAMP>, an alternative version of <SAMP>std::search()</SAMP> takes an optional binary predicate that is used to compare elements from the two sequences.</P>
<P>What determines the speed of the search? In the worst case, the number of comparisons performed by the algorithm <SAMP>std::search()</SAMP> is the product of the number of elements in the two sequences. Except in rare cases, however, this worst case behavior is highly unlikely.</P>
<A NAME="1335"><H3>13.3.5 Find the Last Occurrence of a Sub-Sequence</H3></A>
<A NAME="idx289"><!></A>
<P>The algorithm <SAMP>std::find_end()</SAMP> is used to locate the beginning of the last occurrence of a particular sub-sequence within a larger sequence. The easiest example to understand is the problem of looking for a particular substring within a larger string, although the algorithm can be generalized to other uses. The arguments are assumed to have at least the capabilities of forward iterators.</P>
<UL><PRE>
namespace std {
ForwardIterator find_end
(ForwardIterator first1, ForwardIterator last1,
ForwardIterator first2, ForwardIterator last2
[, BinaryPredicate ]);
}
</PRE></UL>
<P>Suppose, for example, that we want to discover the location of the last occurrence of the string <SAMP>"le"</SAMP> in the string <SAMP>"The road less traveled"</SAMP>. The solution to this problem is shown in the example program. If no appropriate match is found, the value returned is the past-the-end iterator for the first sequence.</P>
<A NAME="idx290"><!></A>
<UL><PRE>
void find_end_example ()
// illustrate the use of the find_end algorithm
// see alg2.cpp for complete source code
{
char *base = "The road less traveled";
char *text = "le";
char *where = std::find(base, base + std::strlen(base),
text, text + std::strlen(text));
if (*where != '\0')
std::cout &lt;&lt; "substring position: "
&lt;&lt; where - base &lt;&lt; std::endl;
else
std::cout &lt;&lt; "substring does not occur in text" &lt;&lt; std::endl;
}
</PRE></UL>
<P>Note that this algorithm, unlike many that manipulate two sequences, uses a starting and ending <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> pair for both sequences, not just the first sequence.</P>
<P>Like the algorithms <SAMP>std::find_first_of()</SAMP> and <SAMP>std::search()</SAMP>, an alternative version of <SAMP>std::find_end()</SAMP> takes an optional binary predicate that is used to compare elements from the two sequences.</P>
<P>What determines the speed of the search? As with <SAMP>std::search()</SAMP>, in the worst case, the number of comparisons performed by the algorithm <SAMP>std::find_end()</SAMP> is the product of the number of elements in the two sequences. </P>
<A NAME="1336"><H3>13.3.6 Locate Maximum or Minimum Element</H3></A>
<A NAME="idx291"><!></A>
<P>The functions <SAMP>std::max()</SAMP> and <SAMP>std::min()</SAMP> can be used to find the maximum and minimum of a pair of values. These can optionally take a third argument that defines the comparison function to use in place of the less-than operator <SAMP>&lt;</SAMP>. The arguments are values, not <B><I><A HREF="../stdlibref/iterators.html">iterators</A></I></B>:</P>
<UL><PRE>
namespace std{
template &lt;class T&gt;
const T&amp; max(const T&amp; a, const T&amp; b [, Compare ] );
template &lt;class T&gt;
const T&amp; min(const T&amp; a, const T&amp; b [, Compare ] );
}
</PRE></UL>
<A NAME="idx292"><!></A>
<P>The maximum and minimum functions are generalized to entire sequences by the generic algorithms <SAMP>std::max_element()</SAMP> and <SAMP>std::min_element()</SAMP>. For these functions the arguments are input iterators.</P>
<UL><PRE>
namespace std {
ForwardIterator max_element (ForwardIterator first,
ForwardIterator last
[, Compare ] );
ForwardIterator min_element (ForwardIterator first,
ForwardIterator last
[, Compare ] );
}
</PRE></UL>
<P>These algorithms return an <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> that denotes the largest or smallest of the values in a sequence, respectively. Should more than one value satisfy the requirement, the result yielded is the first satisfactory value. Both algorithms can optionally take a third argument, which is the function to be used as the comparison operator in place of the default operator.</P>
<P>The example program illustrates several uses of these algorithms. The function named <SAMP>split()</SAMP> that was used to divide a string into words in the <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> example is described in <A HREF="12-3.html">Section&nbsp;12.3</A>. The function <SAMP>randomInteger()</SAMP> is described in <A HREF="2-5.html">Section&nbsp;2.5</A>.</P>
<A NAME="idx293"><!></A>
<UL><PRE>
void max_min_example()
// illustrates use of max_element and min_element algorithms
// see alg2.cpp for complete source code
{
// make a vector of random numbers between 0 and 99
std::vector&lt;int&gt; numbers(25);
for (int i = 0; i &lt; 25; i++)
numbers[i] = randomInteger(100);
// print the maximum
std::vector&lt;int&gt;::iterator max =
std::max_element(numbers.begin(), numbers.end());
std::cout &lt;&lt; "largest value was " &lt;&lt; * max &lt;&lt; std::endl;
// example using strings
std::string text =
"It was the best of times, it was the worst of times.";
std::list&lt;std::string&gt; words;
std::split (text, " .,!:;", words);
std::cout &lt;&lt; "The smallest word is "
&lt;&lt; *std::min_element(words.begin(), words.end())
&lt;&lt; " and the largest word is "
&lt;&lt; *std::max_element(words.begin(), words.end())
&lt;&lt; std::endl;
}
</PRE></UL>
<P>The maximum and minimum algorithms can be used with all the datatypes provided by the C++ Standard Library. However, for the ordered datatypes <B><I><A HREF="../stdlibref/set.html">set</A></I></B> and <B><I><A HREF="../stdlibref/map.html">map</A></I></B>, the maximum or minimum values are more easily accessed as the first or last elements in the structure.</P>
<A NAME="1337"><H3>13.3.7 Locate the First Mismatched Elements in Parallel Sequences</H3></A>
<A NAME="idx294"><!></A>
<P>The name <SAMP>std::mismatch()</SAMP> might lead you to think this algorithm is the inverse of the <SAMP>std::equal()</SAMP> algorithm, which determines if two sequences are equal (<A HREF="13-6.html#1364">Section&nbsp;13.6.4</A>). Instead, the <SAMP>std::mismatch()</SAMP> algorithm returns a <B><I><A HREF="../stdlibref/pair.html">pair</A></I></B> of iterators that together indicate the first positions where two parallel sequences have differing elements. The structure <B><I>pair</I></B> is described in <A HREF="9-1.html">Section&nbsp;9.1</A> and <A HREF="9-2.html#921">Section&nbsp;9.2.1</A>. </P>
<P>The second sequence is denoted only by a starting position, without an ending position. It is assumed, but not checked, that the second sequence contains at least as many elements as the first. The arguments and return type for <SAMP>mismatch()</SAMP> can be described as follows:</P>
<UL><PRE>
namespace std {
pair&lt;InputIterator, InputIterator&gt; mismatch
(InputIterator first1, InputIterator last1,
InputIterator first2 [, BinaryPredicate ] );
}
</PRE></UL>
<P>The elements of the two sequences are examined in parallel, element by element. When a mismatch is found, that is, a point where the two sequences differ, then a <B><I><A HREF="../stdlibref/pair.html">pair</A></I></B> containing <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s denoting the locations of the two differing elements is constructed and returned. If the first sequence is exhausted before discovering any mismatched elements, then the resulting <B><I>pair</I></B> contains the ending value for the first sequence, and the last value examined in the second sequence. The second sequence need not yet be exhausted.</P>
<P>The example program illustrates the use of this procedure. The function <SAMP>std::mismatch_test()</SAMP> takes as arguments two <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> values. These are lexicographically compared and a message printed indicating their relative ordering. This is similar to the analysis performed by the <SAMP>std::lexicographic_compare()</SAMP> algorithm, although that function simply returns a boolean value. </P>
<P>Because the <SAMP>std::mismatch()</SAMP> algorithm assumes the second sequence is at least as long as the first, a comparison of the two string lengths is performed first, and the arguments are reversed if the second string is shorter than the first. After the call on <SAMP>std::mismatch()</SAMP>, the elements of the resulting <B><I><A HREF="../stdlibref/pair.html">pair</A></I></B> are separated into their component parts. These parts are then tested to determine the appropriate ordering.</P>
<A NAME="idx295"><!></A>
<UL><PRE>
void mismatch_test (char *a, char *b)
// illustrates the use of the mismatch algorithm
// see alg2.cpp for complete source code
{
std::pair&lt;char *, char *&gt; differPositions(0, 0);
char *aDiffPosition;
char *bDiffPosition;
if (std::strlen(a) &lt; std::strlen(b)) {
// make sure longer string is second
differPositions = std::mismatch(a, a + std::strlen(a), b);
aDiffPosition = differPositions.first;
bDiffPosition = differPositions.second;
}
else {
differPositions = std::mismatch(b, b + std::strlen(b), a);
// note following reverse ordering
aDiffPosition = differPositions.second;
bDiffPosition = differPositions.first;
}
// compare resulting values
std::cout &lt;&lt; "string " &lt;&lt; a;
if (*aDiffPosition == *bDiffPosition)
std::cout &lt;&lt; " is equal to ";
else if (*aDiffPosition &lt; *bDiffPosition)
std::cout &lt;&lt; " is less than ";
else
std::cout &lt;&lt; " is greater than ";
std::cout &lt;&lt; b &lt;&lt; std::endl;
}
</PRE></UL>
<P>A second form of the <SAMP>std::mismatch()</SAMP> algorithm is similar to this one, except it accepts a binary predicate as a fourth argument. This binary function is used to compare elements in place of <SAMP>operator==()</SAMP>.</P>
<BR>
<HR>
<A HREF="13-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,377 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>In-Place Transformations</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-5.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>13.4 In-Place Transformations</H2>
<A NAME="idx296"><!></A>
<P>The next category of algorithms that we examine is used to modify and transform sequences without moving them from their original storage locations. </P>
<BLOCKQUOTE><HR><B>
NOTE -- The example functions described in the following sections can be found in the file alg3.cpp.
</B><HR></BLOCKQUOTE>
<P>A few of these routines, such as <SAMP>std::replace()</SAMP>, include a <I>copy</I> version as well as the original in-place transformation algorithms. For the others, should it be necessary to preserve the original, a copy of the sequence should be created before the transformations are applied. For example, the following code illustrates how one can place the reversal of one <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> into another newly allocated <B><I>vector</I></B>:</P>
<UL><PRE>
std::vector&lt;int&gt; newVec(aVec.size());
std::copy(aVec.begin(), aVec.end(), newVec.begin());// first copy
std::reverse(newVec.begin(), newVec.end()); // then reverse
</PRE></UL>
<P>Many of the algorithms described as sequence generating operations, such as<SAMP> std::transform()</SAMP> or <SAMP>std::partial_sum()</SAMP>, can also modify a value in place by simply using the same iterator as both input and output specification (see <A HREF="13-7.html#1371">Section&nbsp;13.7.1</A> and <A HREF="13-7.html#1372">Section&nbsp;13.7.2</A>).</P>
<A NAME="1341"><H3>13.4.1 Reverse Elements in a Sequence</H3></A>
<A NAME="idx297"><!></A>
<P>The algorithm <SAMP>std::reverse()</SAMP> reverses the elements in a sequence so that the last element becomes the new first, and the first element the new last. The arguments are assumed to be bidirectional iterators, and no value is returned.</P>
<UL><PRE>
namespace std {
void reverse (BidirectionalIterator first,
BidirectionalIterator last);
}
</PRE></UL>
<A NAME="idx298"><!></A>
<P>The example program illustrates two uses of this algorithm. In example 1, an array of character values is reversed. The algorithm <SAMP>std::reverse()</SAMP> can also be used with <B><I><A HREF="../stdlibref/list.html">list</A></I></B> values, as shown in example 2. In this example, a <B><I>list</I></B> is initialized with the values <SAMP>2</SAMP> to <SAMP>11</SAMP> in increasing order. (This is accomplished using the <B><I>iotaGen</I></B> function object introduced in <A HREF="3-2.html#322-3">Section&nbsp;3.2.2.3</A>). The <B><I>list</I></B> is then reversed, which results in the list holding the values <SAMP>11</SAMP> to <SAMP>2</SAMP> in decreasing order. Note, however, that the <B><I>list</I></B> data structure also provides its own <SAMP>std::reverse()</SAMP> member function.</P>
<A NAME="idx299"><!></A>
<UL><PRE>
void reverse_example()
// illustrates the use of the reverse algorithm
// see alg3.cpp for complete source code
{
// example 1, reversing a string
char *text = "Rats live on no evil star";
std::reverse(text, text + strlen(text));
std::cout &lt;&lt; text &lt;&lt; std::endl;
// example 2, reversing a list
std::list&lt;int&gt; iList;
std::generate_n(std::inserter(iList, iList.begin()),
10, iotaGen(2));
std::reverse(iList.begin(), iList.end());
}
</PRE></UL>
<A NAME="1342"><H3>13.4.2 Replace Certain Elements With Fixed Value</H3></A>
<A NAME="idx300"><!></A>
<P>The algorithms <SAMP>std::replace()</SAMP> and <SAMP>std::replace_if()</SAMP> are used to replace occurrences of certain elements with a new value. For both algorithms, the new value is the same, no matter how many replacements are performed. Using the algorithm <SAMP>std::replace()</SAMP>, all occurrences of a particular test value are replaced with the new value. In the case of <SAMP>std::replace_if()</SAMP>, all elements that satisfy a predicate function are replaced by a new value. The <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> arguments must be forward iterators.</P>
<A NAME="idx301"><!></A>
<P>The algorithms <SAMP>std::replace_copy()</SAMP> and <SAMP>std::replace_copy_if()</SAMP> are similar to <SAMP>std::replace()</SAMP> and <SAMP>std::replace_if()</SAMP>, however, they leave the original sequence intact and place the revised values into a new sequence, which may be a different type.</P>
<UL><PRE>
namespace std {
void replace(ForwardIterator first, ForwardIterator last,
const T&amp;, const T&amp;);
void replace_if(ForwardIterator first, ForwardIterator last,
Predicate, const T&amp;);
OutputIterator replace_copy(InputIterator, InputIterator,
OutputIterator, const T&amp;, const T&amp;);
OutputIterator replace_copy(InputIterator, InputIterator,
OutputIterator, Predicate,
const T&amp;);
}
</PRE></UL>
<P>In the example program, a vector is initially assigned the values <SAMP>0 1 2 3 4 5 4 3 2 1 0</SAMP>. A call on <SAMP>std::replace()</SAMP> replaces the value <SAMP>3</SAMP> with the value <SAMP>7</SAMP>, resulting in the vector <SAMP>0 1 2 7 4 5 4 7 2 1 0</SAMP>. The invocation of <SAMP>std::replace_if()</SAMP> replaces all even numbers with the value <SAMP>9</SAMP>, resulting in the vector <SAMP>9 1 9 7 9 5 9 7 9 1 9</SAMP>.</P>
<A NAME="idx302"><!></A>
<UL><PRE>
void replace_example()
// illustrates the use of the replace algorithm
// see alg3.cpp for complete source code
{
// make vector 0 1 2 3 4 5 4 3 2 1 0
std::vector&lt;int&gt; numbers(11);
for (int i = 0; i &lt; 11; i++)
numbers[i] = i &lt; 5 ? i : 10 - i;
// replace 3 by 7
std::replace(numbers.begin(), numbers.end(), 3, 7);
// replace even numbers by 9
std::replace_if(numbers.begin(), numbers.end(), isEven, 9);
// illustrate copy versions of replace
int aList[] = {2, 1, 4, 3, 2, 5};
int bList[6], cList[6], j;
std::replace_copy(aList, aList+6, &amp;bList[0], 2, 7);
std::replace_copy_if(bList, bList+6, &amp;cList[0],
std::bind2nd(greater&lt;int&gt;(), 3), 8);
}
</PRE></UL>
<P>The example program also illustrates the use of the <SAMP>std::replace_copy()</SAMP> algorithms. First, an array containing the values <SAMP>2 1 4 3 2 5</SAMP> is created. This is modified by replacing the <SAMP>2</SAMP> values with <SAMP>7</SAMP>, resulting in the array <SAMP>7 1 4 3 7 5</SAMP>. Next, all values larger than <SAMP>3</SAMP> are replaced with the value <SAMP>8</SAMP>, resulting in the array values <SAMP>8 1 8 3 8 8</SAMP>. In the latter case the <SAMP>std::bind2nd()</SAMP> adaptor is used to modify the binary greater-than function by binding the second argument to the constant value <SAMP>3</SAMP>, thereby creating the unary function<SAMP> x &gt; 3</SAMP>.</P>
<A NAME="1343"><H3>13.4.3 Rotate Elements Around a Midpoint</H3></A>
<A NAME="idx303"><!></A>
<P>A <I>rotation</I> of a sequence divides the sequence into two sections and swaps the order of the sections, while maintaining the order of elements within each section. Suppose, for example, that we have the values <SAMP>1</SAMP> to <SAMP>10</SAMP> in sequence:</P>
<P><SAMP>1 2 3 4 5 6 7 8 9 10</SAMP></P>
<P>If we were to rotate around the element <SAMP>7</SAMP>, the values <SAMP>7</SAMP> to <SAMP>10</SAMP> would be moved to the beginning, while the elements <SAMP>1</SAMP> to <SAMP>6</SAMP> would be moved to the end. This would result in the following sequence:</P>
<P><SAMP>7 8 9 10 1 2 3 4 5 6</SAMP> </P>
<A NAME="idx304"><!></A>
<P>When you invoke the algorithm <SAMP>std::rotate()</SAMP>, the starting point, midpoint, and past-the-end location are all denoted by forward iterators:</P>
<UL><PRE>
namespace std{
void rotate (ForwardIterator first, ForwardIterator middle,
ForwardIterator last);
}
</PRE></UL>
<P>The <I>prefix</I> portion, the set of elements following the start and not including the midpoint, is swapped with the <I>suffix</I>, the set of elements between the midpoint and the past-the-end location. Note, as in the previous example, that these two segments need not be the same length.</P>
<A NAME="idx305"><!></A>
<UL><PRE>
void rotate_example()
// illustrates the use of the rotate algorithm
// see alg3.cpp for complete source code
{
// create the list 1 2 3 ... 10
std::list&lt;int&gt; iList;
std::generate_n(std::inserter(iList, iList.begin()), 10,
iotaGen(1));
// find the location of the seven
std::list&lt;int&gt;::iterator&amp; middle =
std::find(iList.begin(), iList.end(), 7);
// now rotate around that location
std::rotate(iList.begin(), middle, iList.end());
// rotate again around the same location
std::list&lt;int&gt; cList;
std::rotate_copy(iList.begin(), middle, iList.end(),
std::inserter(cList, cList.begin()));
}
</PRE></UL>
<P>The example program first creates a list of the integers in order from <SAMP>1</SAMP> to <SAMP>10</SAMP>. Next, the <SAMP>std::find()</SAMP> algorithm (<A HREF="13-3.html#1331">Section&nbsp;13.3.1</A>) is used to find the location of the element <SAMP>7</SAMP>. This is used as the midpoint for the rotation.</P>
<P>A second form of <SAMP>std::rotate()</SAMP> copies the elements into a new sequence, rather than rotating the values in place. This is also shown in the example program, which once again rotates around the middle position that now contains a <SAMP>3</SAMP>. The resulting list is <SAMP>3 4 5 6 7 8 9 10 1 2</SAMP>. The values held in <SAMP>iList</SAMP> remain unchanged.</P>
<A NAME="1344"><H3>13.4.4 Partition a Sequence into Two Groups</H3></A>
<A NAME="idx306"><!></A>
<P>A <I>partition </I>is formed by moving all the elements that satisfy a predicate to one end of a sequence, and all the elements that fail to satisfy the predicate to the other end. Partitioning elements is a fundamental step in certain sorting algorithms, such as <SAMP>quicksort</SAMP>.</P>
<UL><PRE>
namespace std {
BidirectionalIterator partition
(BidirectionalIterator, BidirectionalIterator, Predicate);
BidirectionalIterator stable_partition
(BidirectionalIterator, BidirectionalIterator, Predicate);
}
</PRE></UL>
<A NAME="idx307"><!></A>
<P>There are two forms of partition supported in the C++ Standard Library. The first, provided by the algorithm <SAMP>std::partition()</SAMP>, guarantees only that the elements are divided into two groups. The result value is an <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> that describes the final midpoint between the two groups; it is one past the end of the first group. </P>
<P>In the example program, the initial <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> contains the values <SAMP>1</SAMP> to <SAMP>10</SAMP> in order. The partition moves the even elements to the front, and the odd elements to the end. This results in the <B><I>vector</I></B> holding the values <SAMP>10 2 8 4 6 5 7 3 9 1</SAMP>, and the midpoint <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> pointing to the element <SAMP>5</SAMP>.</P>
<A NAME="idx308"><!></A>
<UL><PRE>
void partition_example()
// illustrates the use of the partition algorithm
// see alg3.cpp for complete source code
{
// first make the vector 1 2 3 ... 10
std::vector&lt;int&gt; numbers(10);
std::generate(numbers.begin(), numbers.end(), iotaGen(1));
// now put the even values low, odd high
std::vector&lt;int&gt;::iterator result =
std::partition(numbers.begin(), numbers.end(), isEven);
std::cout &lt;&lt; "middle location "
&lt;&lt; result - numbers.begin() &lt;&lt; std::endl;
// now do a stable partition
std::generate(numbers.begin(), numbers.end(), iotaGen(1));
std::stable_partition(numbers.begin(), numbers.end(), isEven);
}
</PRE></UL>
<A NAME="idx309"><!></A>
<P>The relative order of the elements within a partition in the resulting <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> may not be the same as the values in the original <B><I>vector</I></B>. For example, the value <SAMP>4</SAMP> preceded the element <SAMP>8</SAMP> in the original, but may follow the element <SAMP>8</SAMP> in the result. A second version of partition, named <SAMP>std::stable_partition()</SAMP>, guarantees the ordering of the resulting values. For the input shown in the example, the stable partition would result in the sequence <SAMP>2 4 6 8 10 1 3 5 7 9</SAMP>. The <SAMP>std::stable_partition()</SAMP> algorithm is slightly slower and uses more memory than the <SAMP>std::partition()</SAMP> algorithm, so when the order of elements is not important you should use <SAMP>std::partition()</SAMP>.</P>
<P>While there is a unique <SAMP>std::stable_ partition()</SAMP> for any sequence, the <SAMP>std::partition()</SAMP> algorithm can return any number of values. For example, the following are all legal partitions of the sample problem:</P>
<UL><PRE> 2 4 6 8 10 1 3 5 7 9
10 8 6 4 2 5 7 9 3 1
2 6 4 8 10 3 5 7 9 1
6 4 2 10 8 5 3 7 9 1
</PRE></UL>
<A NAME="1345"><H3>13.4.5 Generate Permutations in Sequence</H3></A>
<A NAME="idx310"><!></A>
<P>A <I>permutation</I> is a rearrangement of values. If values such as integers, characters, or words can be compared against each other, then it is possible to systematically construct all permutations of a sequence. For example, there are two permutations of two values, six permutations of three values, and 24 permutations of four values. </P>
<P>The permutation generating algorithms have the following definition:</P>
<UL><PRE>
namespace std {
bool next_permutation(BidirectionalIterator first,
BidirectionalIterator last
[, Compare ] );
bool prev_permutation(BidirectionalIterator first,
BidirectionalIterator last
[, Compare ] );
}
</PRE></UL>
<A NAME="idx311"><!></A>
<P>The second example in the sample program illustrates the same idea, using pointers to character arrays instead of integers. In this case, a different comparison function must be supplied, since the default operator would simply compare pointer addresses. </P>
<A NAME="idx312"><!></A>
<UL><PRE>
bool nameCompare (char *a, char *b) { return strcmp(a, b) &lt;= 0; }
void permutation_example()
// illustrates the use of the next_permutation algorithm
// see alg3.cpp for complete source code
{
// example 1
int start [] = { 1, 2, 3 };
do {
std::copy(start, start + 3, ostrm_iter_type (std::cout, " "));
std::cout &lt;&lt; std::endl;
} while (std::next_permutation (start, start + 3));
// example 2
const char alpha[] = "Alpha";
const char beta[] = "Beta";
const char gamma[] = "Gamma";
const char* names[] = { alpha, beta, gamma };
typedef std::ostream_iterator&lt;const char*, char,
std::char_traits&lt;char&gt; &gt; Iter;
do {
std::copy (names, names + 3, Iter (std::cout, " "));
std::cout &lt;&lt; std::endl;
} while (std::next_permutation (names, names + 3, nameCompare));
// example 3
char word[] = "bela";
do
std::cout &lt;&lt; word &lt;&lt; ' ';
while (std::prev_permutation (word, &amp;word[4]));
std::cout &lt;&lt; std::endl;
}
</PRE></UL>
<P>Example 3 in the sample program illustrates the use of the reverse permutation algorithm, which generates values in reverse sequence. This example also begins in the middle of a sequence, rather than at the beginning. The remaining permutations of the word <I>bela</I> are: <SAMP>beal</SAMP>, <SAMP>bale</SAMP>, <SAMP>bael</SAMP>, <SAMP>aleb</SAMP>, <SAMP>albe</SAMP>, <SAMP>aelb</SAMP>, <SAMP>aebl</SAMP>, <SAMP>able</SAMP>, and <SAMP>abel.</SAMP></P>
<P>Permutations can also be ordered so that the smallest permutation lists values smallest to largest, and the largest sequence lists values largest to smallest. For example, consider the permutations of the integers <SAMP>1 2 3</SAMP>. Taken in order, the six permutations of these values are:</P>
<UL><P><SAMP>123</SAMP></P></UL>
<UL><P><SAMP>132</SAMP></P></UL>
<UL><P><SAMP>213</SAMP></P></UL>
<UL><P><SAMP>231</SAMP></P></UL>
<UL><P><SAMP>312</SAMP></P></UL>
<UL><P><SAMP>321</SAMP></P></UL>
<P>Notice that in the first permutation the values are all ascending, while in the last permutation they are all descending.</P>
<A NAME="1346"><H3>13.4.6 Merge Two Adjacent Sequences into One</H3></A>
<A NAME="idx313"><!></A>
<P>A <I>merge</I> takes two ordered sequences and combines them into a single ordered sequence, interleaving elements from each collection as necessary to generate the new list. The <SAMP>inplace_merge()</SAMP> algorithm assumes a sequence is divided into two adjacent sections, each of which is ordered. The merge combines the two sections into one, moving elements as necessary. The alternative <SAMP>merge()</SAMP> algorithm (<A HREF="6-2.html#623-1">Section&nbsp;6.2.3.1</A> and <A HREF="14-5.html">Section&nbsp;14.5</A>) can be used to merge two separate sequences into one. </P>
<P>The arguments to <SAMP>inplace_merge()</SAMP> must be bidirectional iterators.</P>
<UL><PRE>
namespace std {
void inplace_merge (BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last
[, BinaryFunction ] );
}
</PRE></UL>
<P>The example program illustrates the use of the <SAMP>inplace_merge()</SAMP> algorithm with a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> and with a <B><I><A HREF="../stdlibref/list.html">list</A></I></B>. The sequence <SAMP>0 2 4 6 8 1 3 5 7 9</SAMP> is placed into a <B><I>vector</I></B>. A <SAMP>find()</SAMP> call (<A HREF="13-3.html#1331">Section&nbsp;13.3.1</A>) is used to locate the beginning of the odd number sequence. The two calls on <SAMP>inplace_merge()</SAMP> then combine the two sequences into one.</P>
<A NAME="idx314"><!></A>
<UL><PRE>
void inplace_merge_example()
// illustrate the use of the inplace_merge algorithm
// see alg3.cpp for complete source code
{
// first generate the sequence 0 2 4 6 8 1 3 5 7 9
std::vector&lt;int&gt; numbers(10);
for (int i = 0; i &lt; 10; i++)
numbers[i] = i &lt; 5 ? 2 * i : 2 * (i - 5) + 1;
// then find the middle location
std::vector&lt;int&gt;::iterator midvec =
std::find(numbers.begin(), numbers.end(), 1);
// copy them into a list
std::list&lt;int&gt; numList;
std::copy(numbers.begin(), numbers.end(),
std::inserter (numList, numList.begin()));
std::list&lt;int&gt;::iterator midList =
std::find(numList.begin(), numList.end, 1);
// now merge the lists into one
std::inplace_merge(numbers.begin(), midvec, numbers.end());
std::inplace_merge(numList.begin(), midList, numList.end());
}
</PRE></UL>
<A NAME="1347"><H3>13.4.7 Randomly Rearrange Elements in a Sequence</H3></A>
<A NAME="idx315"><!></A>
<P>The algorithm <SAMP>std::random_shuffle()</SAMP> randomly rearranges the elements in a sequence. Exactly <SAMP>n</SAMP> swaps are performed, where <SAMP>n</SAMP> represents the number of elements in the sequence. Of course, the results are unpredictable. Because the arguments must be random access <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s, this algorithm can only be used with <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>s, <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>s, or ordinary pointers; it cannot be used with <B><I><A HREF="../stdlibref/list.html">list</A></I></B>s, <B><I><A HREF="../stdlibref/set.html">set</A></I></B>s, or <B><I><A HREF="../stdlibref/map.html">map</A></I></B>s.</P>
<UL><PRE>
namespace std {
void random_shuffle(RandomAccessIterator first,
RandomAccessIterator last
[, Generator ] );
}
</PRE></UL>
<P>An alternative version of the algorithm uses the optional third argument. This value must be a random number generator. This generator must take as an argument a positive value <SAMP>m</SAMP> and return a value between <SAMP>0</SAMP> and <SAMP>m-1</SAMP>. As with the <SAMP>std::generate()</SAMP> algorithm, this random number function can be any type of object that responds to the function invocation operator.</P>
<A NAME="idx316"><!></A>
<UL><PRE>
void random_shuffle_example()
// illustrates the use of the random_shuffle algorithm
// see alg3.cpp fr complete source code
{
// first make the vector containing 1 2 3 ... 10
std::vector&lt;int&gt; numbers;
std::generate(numbers.begin(), numbers.end(), iotaGen(1));
// then randomly shuffle the elements
std::random_shuffle(numbers.begin(), numbers.end());
// do it again, with explicit random number generator
struct RandomInteger {
operator() (int m) { return rand() % m; }
} random;
std::random_shuffle(numbers.begin(), numbers.end(), random);
}
</PRE></UL>
<BR>
<HR>
<A HREF="13-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-5.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,154 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Removal Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-6.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>13.5 Removal Algorithms</H2>
<A NAME="idx317"><!></A>
<P>The <SAMP>std::remove()</SAMP> algorithm and the <SAMP>std::unique()</SAMP> algorithm can be somewhat confusing the first time you encounter them. Both claim to remove certain values from a sequence, yet neither reduces the size of the sequence. Both operate by moving the values that are to be <I>retained</I> to the front of the sequence, and returning an <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> that describes where this sequence ends. Elements after this <B><I>iterator</I></B> are simply the original sequence values, left unchanged. This is necessary because the generic algorithm has no knowledge of the container it is working on. It only has a generic iterator. This is part of the price we pay for generic algorithms. In most cases you will want to use this <B><I>iterator</I></B> result as an argument to the <SAMP>std::erase()</SAMP> member function for the container, removing the values from the <B><I>iterator</I></B> to the end of the sequence.</P>
<P>Let us illustrate this with a simple example. Suppose we want to remove the even numbers from the sequence <SAMP>1 2 3 4 5 6 7 8 9 10</SAMP>, something we could do with the <SAMP>std::remove_if()</SAMP> algorithm. Applying this algorithm would leave us with the following sequence:</P>
<P><SAMP>1 3 5 7 9 | 6 7 8 9 10</SAMP></P>
<P>The vertical bar here represents the position of the iterator returned by the <SAMP>std::remove_if()</SAMP> algorithm. Notice that the five elements before the bar represent the result we want, while the five values after the bar are simply the original contents of those locations. Using this <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> value along with the end-of-sequence iterator as arguments to <SAMP>std::erase(),</SAMP> we can eliminate the unwanted values, and obtain the desired result.</P>
<P>Both the algorithms described here have an alternative <I>copy</I> version. The copy version of the algorithms leaves the original unchanged, and places the preserved elements into an output sequence.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The example functions described in this section can be found in the file alg4.cpp.
</B><HR></BLOCKQUOTE>
<A NAME="1351"><H3>13.5.1 Remove Unwanted Elements</H3></A>
<A NAME="idx318"><!></A>
<P>The algorithm <SAMP>std::remove()</SAMP> eliminates unwanted values from a sequence. As with the <SAMP>std::find()</SAMP> algorithm, these can be values that match a specific constant, or values that satisfy a given predicate. The declaration of the argument types is as follows:</P>
<UL><PRE>
namespace std {
ForwardIterator remove(ForwardIterator first,
ForwardIterator last, const T&amp;);
ForwardIterator remove_if(ForwardIterator first,
ForwardIterator last, Predicate);
}
</PRE></UL>
<P>The algorithm <SAMP>std::remove()</SAMP> copies values to the front of the sequence, overwriting the location of the removed elements. All elements not removed remain in their relative order. Once all values have been examined, the remainder of the sequence is left unchanged. The iterator returned as the result of the operation provides the end of the new sequence. For example, eliminating the element <SAMP>2</SAMP> from the sequence <SAMP>1 2 4 3 2</SAMP> results in the sequence <SAMP>1 4 3 3 2</SAMP>, with the <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> returned as the result pointing at the second <SAMP>3</SAMP>. This value can be used as argument to <SAMP>std::erase()</SAMP> in order to eliminate the remaining elements <SAMP>3</SAMP> and <SAMP>2</SAMP>, as illustrated in the example program.</P>
<P>A copy version of the algorithms copies values to an output sequence, rather than making transformations in place.</P>
<UL><PRE>
namespace std {
OutputIterator remove_copy
(InputIterator first, InputIterator last,
OutputIterator result, const T&amp;);
OutputIterator remove_copy_if
(InputIterator first, InputIterator last,
OutputIterator result, Predicate);
}
</PRE></UL>
<P>The use of <SAMP>std::remove()</SAMP> is shown in the following program.</P>
<A NAME="idx319"><!></A>
<UL><PRE>
void remove_example()
// illustrates the use of the remove algorithm
// see alg4.cpp for complete source code
{
// create a list of numbers
int data[] = {1, 2, 4, 3, 1, 4, 2};
std::list&lt;int&gt; aList;
std::copy(data, data+7, std::inserter(aList, aList.begin()));
// remove 2's, copy into new list
std::list&lt;int&gt; newList;
std::remove_copy(aList.begin(), aList.end(),
std::back_inserter(newList), 2);
// remove 2's in place
std::list&lt;int&gt;::iterator where;
where = std::remove(aList.begin(), aList.end(), 2);
aList.erase(where, aList.end());
// remove all even values
where = std::remove_if(aList.begin(), aList.end(), isEven);
aList.erase(where, aList.end());
}
</PRE></UL>
<A NAME="1352"><H3>13.5.2 Remove Runs of Similar Values</H3></A>
<A NAME="idx320"><!></A>
<P>The algorithm <SAMP>std::unique()</SAMP> moves through a linear sequence, eliminating all but the first element from every consecutive group of equal elements. The argument sequence is described by forward iterators:</P>
<UL><PRE>
namespace std {
ForwardIterator unique (ForwardIterator first,
ForwardIterator last [, BinaryPredicate ] );
}
</PRE></UL>
<P>As the algorithm moves through the collection, elements are moved to the front of the sequence, overwriting the existing elements. Once all unique values are identified, the remainder of the sequence is left unchanged. For example, a sequence such as <SAMP>1 3 3 2 2 2 4</SAMP> is changed into <SAMP>1 3 2 4 | 2 2 4</SAMP>. We use a vertical bar to indicate the location returned by the iterator result value. This location marks the end of the unique sequence, and the beginning of the left-over elements. With most containers, the value returned by the algorithm can be used as an argument in a subsequent call on <SAMP>std::erase()</SAMP> to remove the undesired elements from the collection. This is illustrated in the example program.</P>
<A NAME="idx321"><!></A>
<P>A copy version of the algorithm moves the unique values to an output iterator, rather than making modifications in place. In transforming a <B><I><A HREF="../stdlibref/list.html">list</A></I></B> or <B><I><A HREF="../stdlibref/multiset.html">multiset</A></I></B>, an insert <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> can be used to change the copy operations of the output <B><I>iterator</I></B> into insertions. </P>
<UL><PRE>
namespace std {
OutputIterator unique_copy(InputIterator first,
InputIterator last,
OutputIterator result
[, BinaryPredicate ] );
}
</PRE></UL>
<P>These are illustrated in the sample program:</P>
<A NAME="idx322"><!></A>
<UL><PRE>
void unique_example()
// illustrates the use of the unique algorithm
// see alg4.cpp for complete source code
{
// first make a list of values
int data[] = {1, 3, 3, 2, 2, 4};
std::list&lt;int&gt; aList;
std::set&lt;int&gt; aSet;
std::copy(data, data+6, std::inserter(aList, aList.begin()));
// copy unique elements into a set
std::unique_copy (aList.begin(), aList.end(),
std::inserter(aSet, aSet.begin()));
// copy unique elements in place
std::list&lt;int&gt;::iterator where;
where = std::unique(aList.begin(), aList.end());
// remove trailing values
aList.erase(where, aList.end());
}
</PRE></UL>
<BR>
<HR>
<A HREF="13-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-6.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,247 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Scalar-Producing Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-7.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>13.6 Scalar-Producing Algorithms</H2>
<A NAME="idx323"><!></A>
<P>The next category of algorithms reduces an entire sequence to a single scalar value. Remember that two of these algorithms, <SAMP>std::accumulate()</SAMP> and <SAMP>std::inner_product()</SAMP>, are declared in the <SAMP>&lt;numeric</SAMP>&gt; header file, not the <SAMP>&lt;algorithm</SAMP>&gt; header file as are the other generic algorithms.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The example functions described in the following sections are in the file alg5.cpp.
</B><HR></BLOCKQUOTE>
<A NAME="1361"><H3>13.6.1 Count the Number of Elements That Satisfy a Condition</H3></A>
<A NAME="idx324"><!></A>
<P>The algorithms <SAMP>std::count()</SAMP> and <SAMP>std::count_if()</SAMP> are used to discover the number of elements that match a given value or that satisfy a given predicate, respectively. Each algorithm comes in two forms. The newer form returns the number of matches found, while the older one takes as argument a reference to a counting value, typically an integer, and increments this value. In the latter case the <SAMP>std::count()</SAMP> function itself yields no value. </P>
<P>The newer form of these functions is currently mandated by the standard. The older form is retained for two reasons: first, for backward compatibility, since older versions of the standard contained it; and second, because the newer form requires that a compiler support partial specialization, which most (but not all) compilers now do.</P>
<UL><PRE>
namespace std {
iterator_traits&lt;InputIterator&gt;::distance_type
count(InputIterator first, InputIterator last, const T&amp; value);
iterator_traits&lt;InputIterator&gt;::distance_type
count_if(InputIterator first, InputIterator last,
Predicate pred);
void count(InputIterator first, InputIterator last,
const T&amp;, Size&amp;);
void count_if(InputIterator first, InputIterator last,
Predicate, Size&amp;);
}
</PRE></UL>
<P>The example code fragment illustrates the use of the older form of these algorithms. The call on <SAMP>std::count()</SAMP> counts the number of occurrences of the letter <SAMP>e</SAMP> in a sample string, while the invocation of <SAMP>std::count_if()</SAMP> counts the number of vowels.</P>
<A NAME="idx325"><!></A>
<UL><PRE>
void count_example()
// illustrates the use of the count algorithm
// see alg5.cpp for complete source code
{
int eCount = 0;
int vowelCount = 0;
char *text = "Now is the time to begin";
std::count(text, text + strlen(text), 'e', eCount);
std::count_if(text, text + strlen(text), isVowel, vowelCount);
std::cout &lt;&lt; "There are " &lt;&lt; eCount
&lt;&lt; " letter e's " &lt;&lt; std::endl
&lt;&lt; "and " &lt;&lt; vowelCount &lt;&lt; " vowels in the text:"
&lt;&lt; text &lt;&lt; std::endl;
}
</PRE></UL>
<P>Note that if your compiler does not support partial specialization, you don't have the form of the <SAMP>std::count()</SAMP> algorithms that return the sum as a function result, but only the form that adds to the last argument in its parameter list, which is passed by reference. This means successive calls on these functions can be used to produce a cumulative sum. This also means that you must initialize the variable passed to this last argument location prior to calling one of these algorithms.</P>
<A NAME="1362"><H3>13.6.2 Reduce Sequence to a Single Value</H3></A>
<A NAME="idx326"><!></A>
<P>The result generated by the <SAMP>std::accumulate()</SAMP> algorithm is the value produced by placing a binary operator between each element of a sequence, and evaluating the result. By default the operator is the addition operator, <SAMP>operator+</SAMP>, but this can be replaced by any binary function. An initial value or <I>identity</I> must be provided. This value is returned for empty sequences, and is otherwise used as the left argument for the first calculation. </P>
<UL><PRE>
namespace std {
ContainerType accumulate(InputIterator first,
InputIterator last,
ContainerType initial
[, BinaryFunction ]);
}
</PRE></UL>
<P>The example program illustrates the use of <SAMP>std::accumulate()</SAMP> to produce the sum and product of a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> of <SAMP>int</SAMP> values. In the first case the identity is zero, and the default <SAMP>operator+()</SAMP> is used. In the second invocation, the identity is <SAMP>1</SAMP>, and the multiplication operator named <I>times</I> is explicitly passed as the fourth argument:</P>
<A NAME="idx327"><!></A>
<UL><PRE>
void accumulate_example()
// illustrates the use of the accumulate algorithm
// see alg5.cpp for complete source code
{
int numbers[] = {1, 2, 3, 4, 5};
// first example, simple accumulation
int sum = std::accumulate(numbers, numbers + 5, 0);
int product =
std::accumulate(numbers, numbers + 5, 1,
std::times&lt;int&gt;());
std::cout &lt;&lt; "The sum of the first five integers is "
&lt;&lt; sum &lt;&lt; std::endl;
std::cout &lt;&lt; "The product is " &lt;&lt; product &lt;&lt; std::endl;
// second example, with different types for initial value
std::list&lt;int&gt; nums;
nums = std::accumulate(numbers, numbers+5, nums, intReplicate);
}
std::list&lt;int&gt;&amp; intReplicate(std::list&lt;int&gt;&amp; nums, int n)
// add sequence n to 1 to end of list
{
while (n) nums.push_back(n--);
return nums;
}
</PRE></UL>
<P>Neither the identity value nor the result of the binary function is required to match the container type. This is illustrated in the example program by the invocation of <SAMP>std::accumulate()</SAMP> shown in the second example above. Here the identity is an empty list. The function, shown after the example program, takes as argument a <B><I><A HREF="../stdlibref/list.html">list</A></I></B> and an <SAMP>int</SAMP> value, and repeatedly inserts values into the <B><I>list</I></B>. The values inserted represent a decreasing sequence from the argument down to <SAMP>1</SAMP>. For the example input, the same <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> as in the first example, the resulting <B><I>list</I></B> contains the <SAMP>15</SAMP> values <SAMP>1 2 1 3 2 1 4 3 2 1 5 4 3 2 1</SAMP>.</P>
<A NAME="1363"><H3>13.6.3 Generalized Inner Product</H3></A>
<A NAME="idx328"><!></A>
<P>Assume we have two sequences of <SAMP>n</SAMP> elements each: <SAMP>a1, a2, ... an</SAMP> and <SAMP>b1, b2, ... bn</SAMP><I>.</I> The <I>inner product</I> of the sequences is the sum of the parallel products, that is, the value <SAMP>a1 * b1 + a2 * b2 + ... + an * bn</SAMP>. Inner products occur in a number of scientific calculations. For example, the inner product of a row times a column is the heart of the traditional matrix multiplication algorithm. A generalized inner product uses the same structure, but permits the addition and multiplication operators to be replaced by arbitrary binary functions. The C++ Standard Library includes the following algorithm for computing an inner product:</P>
<UL><PRE>
namespace std {
ContainerType inner_product
(InputIterator first1, InputIterator last1,
InputIterator first2, ContainerType initialValue
[ , BinaryFunction add, BinaryFunction times ]);
}
</PRE></UL>
<A NAME="idx329"><!></A>
<P>The first three arguments to the <SAMP>std::inner_product()</SAMP> algorithm define the two input sequences. The second sequence is specified only by the beginning iterator, and is assumed to contain at least as many elements as the first sequence. The next argument is an initial value, or <I>identity</I>, used for the summation operator. This is similar to the identity used in the <SAMP>std::accumulate()</SAMP> algorithm. In the generalized inner product function, the last two arguments are the binary functions that are used in place of the addition operator and the multiplication operator, respectively.</P>
<P>In the example program, the second invocation illustrates the use of alternative functions as arguments. The multiplication is replaced by an equality test, while the addition is replaced by a logical <I>or</I>. The result is true if any of the pairs are equal, and false otherwise. Using an <I>and</I> in place of the <I>or</I> would have resulted in a test which was true only if <I>all</I> pairs were equal; in effect, the same as the <SAMP>equal()</SAMP> algorithm described in the next section.</P>
<A NAME="idx330"><!></A>
<UL><PRE>
void inner_product_example()
// illustrates the use of the inner_product algorithm
// see alg5.cpp for complete source code
{
int a[] = {4, 3, -2};
int b[] = {7, 3, 2};
// example 1, a simple inner product
int in1 = std::inner_product(a, a+3, b, 0);
std::cout &lt;&lt; "Inner product is " &lt;&lt; in1 &lt;&lt; std::endl;
// example 2, user defined operations
bool anyequal = std::inner_product(a, a+3, b, true,
std::logical_or&lt;bool&gt;(), std::equal_to&lt;int&gt;());
std::cout &lt;&lt; "any equal? " &lt;&lt; anyequal &lt;&lt; std::endl;
}
</PRE></UL>
<A NAME="1364"><H3>13.6.4 Test Two Sequences for Pairwise Equality</H3></A>
<A NAME="idx331"><!></A>
<P>The<SAMP> std::equal()</SAMP> algorithm tests two sequences for pairwises equality. By using an alternative binary predicate, it can also be used for a wide variety of other pair-wise tests of parallel sequences, such as a pairwise test that returns a boolean result. The <SAMP>std::mismatch()</SAMP> algorithm gives the location of elements that fail that test (<A HREF="13-3.html#1337">Section&nbsp;13.3.7</A>).</P>
<P>The arguments of the <SAMP>std::equal()</SAMP> algorithm are simple input <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s:</P>
<UL><PRE>
namespace std {
bool equal(InputIterator first, InputIterator last,
InputIterator first2 [, BinaryPredicate]);
}
</PRE></UL>
<P>The <SAMP>std::equal()</SAMP> algorithm assumes, but does not verify, that the second sequence contains at least as many elements as the first. A <SAMP>true</SAMP> result is generated if all values test equal to their corresponding element. The alternative version of the algorithm substitutes an arbitrary boolean function for the equality test, and returns <SAMP>true</SAMP> if all pair-wise elements satisfy the predicate. In the sample program, this is illustrated by replacing the predicate with the <SAMP>std::greater_equal()</SAMP> function; in this fashion, <SAMP>true</SAMP> is returned only if all values in the first sequence are greater than or equal to their corresponding value in the second sequence.</P>
<A NAME="idx332"><!></A>
<UL><PRE>
void equal_example()
// illustrates the use of the equal algorithm
// see alg5.cpp for complete source code
{
int a[] = {4, 5, 3};
int b[] = {4, 3, 3};
int c[] = {4, 5, 3};
std::cout &lt;&lt; "a = b is: " &lt;&lt; std::equal(a, a+3, b) &lt;&lt; std::endl;
std::cout &lt;&lt; "a = c is: " &lt;&lt; std::equal(a, a+3, c) &lt;&lt; std::endl;
std::cout &lt;&lt; "a pair-wise greater-equal b is: "
&lt;&lt; std::equal(a, a+3, b, std::greater_equal&lt;int&gt;())
&lt;&lt; std::endl;
}
</PRE></UL>
<A NAME="1365"><H3>13.6.5 Lexical Comparison</H3></A>
<A NAME="idx333"><!></A>
<P>A <I>lexical comparison</I> is commonly used to determine the dictionary order of words. In this procedure, the elements or <I>characters</I> of two sequences are compared in pair-wise fashion. As long as characters within a pair match, the algorithm advances to the next pair. When characters within a pair fail to match, the earlier character determines the smaller word. For example, <SAMP>everybody</SAMP> is smaller than <SAMP>everything</SAMP>, since the <SAMP>b</SAMP> in the former word alphabetically precedes the <SAMP>t</SAMP> in the latter. Should one or the other sequence terminate before the other, the terminated sequence is considered the smaller. For example, <SAMP>every</SAMP> precedes both <SAMP>everybody</SAMP> and <SAMP>everything</SAMP>, but comes after <SAMP>eve</SAMP>. Finally, if both sequences terminate at the same time and pair-wise characters match in all cases, the two words are considered equal.</P>
<A NAME="idx334"><!></A>
<P>The <SAMP>std::lexicographical_compare()</SAMP> algorithm implements the concept of lexical comparison, returning <SAMP>true</SAMP> if the first sequence is smaller than the second, and <SAMP>false</SAMP> otherwise. The algorithm is generalized to any sequence. Thus, the <SAMP>std::lexicographical_compare()</SAMP> algorithm can be used with arrays, <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B>s, <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>s, <B><I><A HREF="../stdlibref/list.html">list</A></I></B>s, or any other data structures of the C++ Standard Library.</P>
<UL><PRE>
namespace std {
bool lexicographical_compare
(InputIterator first1, InputIterator last1,
InputIterator first2, InputIterator last2
[, BinaryFunction ] );
}
</PRE></UL>
<P>Unlike most other algorithms that take two sequences as argument, the <SAMP>std::lexicographical_compare()</SAMP> algorithm uses a first and a past-end <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> for <I>both</I> sequences. A variation on the algorithm also takes a fifth argument, which is the binary function used to compare corresponding elements from the two sequences.</P>
<P>The example program illustrates the <SAMP>std::lexicographical_compare()</SAMP> algorithm in use with character sequences, and arrays of integer values.</P>
<A NAME="idx335"><!></A>
<UL><PRE>
void lexicographical_compare_example()
// illustrates the use of the lexicographical_compare algorithm
// see alg5.cpp for complete source code
{
char *wordOne = "everything";
char *wordTwo = "everybody";
std::cout &lt;&lt; "compare everybody to everything "
&lt;&lt; std::lexicographical_compare(wordTwo,
wordTwo + std::strlen(wordTwo),
wordOne,
wordOne + std::strlen(wordOne))
&lt;&lt; std::endl;
int a[] = {3, 4, 5, 2};
int b[] = {3, 4, 5};
int c[] = {3, 5};
std::cout &lt;&lt; "compare a to b:"
&lt;&lt; std::lexicographical_compare(a, a+4, b, b+3)
&lt;&lt; std::endl;
std::cout &lt;&lt; "compare a to c:"
&lt;&lt; std::lexicographical_compare(a, a+4, c, c+2)
&lt;&lt; std::endl;
}
</PRE></UL>
<BR>
<HR>
<A HREF="13-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-7.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,170 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Sequence-Generating Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13-6.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-8.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>13.7 Sequence-Generating Algorithms</H2>
<A NAME="idx336"><!></A>
<P>All of the algorithms described in this section are used to generate a new sequence from an existing sequence by performing some type of transformation. In most cases, the output sequence is described by an output <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>. This means these algorithms can be used to overwrite an existing structure, such as a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>. Alternatively, by using an insert <B><I>iterator</I></B> (see <A HREF="2-4.html">Section&nbsp;2.4</A>), the algorithms can insert the new elements into a variable length structure, such as a <B><I><A HREF="../stdlibref/set.html">set</A></I></B> or <B><I><A HREF="../stdlibref/list.html">list</A></I></B>. Finally, in some cases that we will discuss, the output iterator can be the same as one of the sequences specified by an input <B><I>iterator</I></B>, thereby providing the ability to make an in-place transformation.</P>
<P>The functions <SAMP>std::partial_sum()</SAMP> and <SAMP>std::adjacent_difference()</SAMP> are declared in the header file <SAMP>&lt;numeric&gt;</SAMP>, while the other functions are described in the header file <SAMP>&lt;algorithm&gt;</SAMP>.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The example functions described in the following sections can be found in the file alg6.cpp.
</B><HR></BLOCKQUOTE>
<A NAME="1371"><H3>13.7.1 Transform One or Two Sequences</H3></A>
<A NAME="idx337"><!></A>
<P>The algorithm <SAMP>std::transform()</SAMP> is used either to make a general transformation of a single sequence, or to produce a new sequence by applying a binary function in a pair-wise fashion to corresponding elements from two different sequences. The general definition of the argument and result types are as follows:</P>
<UL><PRE>
namespace std {
OutputIterator transform(InputIterator first,
InputIterator last,
OutputIterator result,
UnaryFunction);
OutputIterator transform(InputIterator first1,
InputIterator last1,
InputIterator first2,
OutputIterator result,
BinaryFunction);
}
</PRE></UL>
<P>The first form applies a unary function to each element of a sequence. In the example program given below, this is used to produce a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> of <SAMP>int</SAMP> values that hold the arithmetic negation of the values in a linked <B><I><A HREF="../stdlibref/list.html">list</A></I></B>. The input and output <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s can be the same, in which case the transformation is applied in-place, as shown in the example program.</P>
<P>The second form takes two sequences and applies the binary function in a pair-wise fashion to corresponding elements. The transaction assumes, but does not verify, that the second sequence has at least as many elements as the first sequence. Once more, the result can either be a third sequence, or one of the two input sequences.</P>
<A NAME="idx338"><!></A>
<UL><PRE>
int square(int n) { return n * n; }
void transform_example()
// illustrates the use of the transform algorithm
// see alg6.cpp for complete source code
{
// generate a list of values 1 to 6
std::list&lt;int&gt; aList;
std::generate_n(std::inserter(aList, aList.begin()),
6, iotaGen(1));
// transform elements by squaring, copy into vector
std::vector&lt;int&gt; aVec(6);
std::transform(aList.begin(), aList.end(), aVec.begin(),
square);
// transform vector again, in place, yielding 4th powers
std::transform(aVec.begin(), aVec.end(), aVec.begin(), square);
// transform in parallel, yielding cubes
std::vector&lt;int&gt; cubes(6);
std::transform(aVec.begin(), aVec.end(), aList.begin(),
cubes.begin(), std::divides&lt;int&gt;());
}
</PRE></UL>
<A NAME="1372"><H3>13.7.2 Partial Sums</H3></A>
<A NAME="idx339"><!></A>
<P>A <I>partial sum</I> of a sequence is a new sequence in which every element is formed by adding the values of all prior elements. For example, the partial sum of the vector <SAMP>1 3 2 4 5</SAMP> is the new vector <SAMP>1 4 6 10 15</SAMP>. The element <SAMP>4</SAMP> is formed from the sum <SAMP>1 + 3</SAMP>, the element <SAMP>6</SAMP> from the sum <SAMP>1 + 3 + 2</SAMP>, and so on. Although the term <I>sum</I> is used in describing the operation, the binary function can be any arbitrary function. The example program illustrates this by computing partial products. </P>
<P>The arguments to the partial sum function are described as follows:</P>
<UL><PRE>
namespace std {
OutputIterator partial_sum(InputIterator first,
InputIterator last,
OutputIterator result
[, BinaryFunction]);
}
</PRE></UL>
<P>By using the same value for both the input iterator and the result, the partial sum can be changed into an in-place transformation.</P>
<A NAME="idx340"><!></A>
<UL><PRE>
void partial_sum_example()
// illustrates the use of the partial sum algorithm
//see alg6.cpp for complete source code
{
// generate values 1 to 5
std::vector&lt;int&gt; aVec(5);
std::generate(aVec.begin(), aVec.end(), iotaGen(1));
// output partial sums
std::partial_sum(aVec.begin(), aVec.end(),
std::ostream_iterator&lt;int&gt; (std::cout, " "));
std::cout &lt;&lt; std::endl;
// output partial products
std::partial_sum(aVec.begin(), aVec.end(),
std::ostream_iterator&lt;int&gt; (std::cout, " "),
std::multiplies&lt;int&gt;() );
std::cout &lt;&lt; std::endl;
}
</PRE></UL>
<A NAME="1373"><H3>13.7.3 Adjacent Differences</H3></A>
<A NAME="idx341"><!></A>
<P>An <I>adjacent difference</I> of a sequence is a new sequence formed by replacing every element with the difference between the element and the immediately preceding element. The first value in the new sequence remains unchanged. For example, a sequence such as <SAMP>(1, 3, 2, 4, 5)</SAMP> is transformed into <SAMP>(1, 3-1, 2-3, 4-2, 5-4)</SAMP>, and in this manner becomes the sequence <SAMP>(1, 2, -1, 2, 1)</SAMP>.</P>
<P>As with the algorithm <SAMP>std::partial_sum()</SAMP>, the term <I>difference</I> is not necessarily accurate, as an arbitrary binary function can be employed. The adjacent sums for this sequence are <SAMP>(1, 4, 5, 6, 9)</SAMP>, for example. The adjacent difference algorithm has the following declaration:</P>
<UL><PRE>
namespace std{
OutputIterator adjacent_difference(InputIterator first,
InputIterator last, OutputIterator result
[, BinaryFunction ]);
}
</PRE></UL>
<P>By using the same <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B> as both input and output <B><I>iterator</I></B>, the adjacent difference operation can be performed in place.</P>
<A NAME="idx342"><!></A>
<UL><PRE>
void adjacent_difference_example()
// illustrates the use of the adjacent difference algorithm
//see alg6.cpp for complete source code
{
// generate values 1 to 5
std::vector&lt;int&gt; aVec(5);
std::generate(aVec.begin(), aVec.end(), iotaGen(1));
// output adjacent differences
std::adjacent_difference(aVec.begin(), aVec.end(),
std::ostream_iterator&lt;int,char&gt;(std::cout," ")),
std::cout &lt;&lt; std::endl;
// output adjacent sums
std::adjacent_difference(aVec.begin(), aVec.end(),
std::ostream_iterator&lt;int,char&gt;(std::cout," "),
std::plus&lt;int&gt;() );
std::cout &lt;&lt; std::endl;
}
</PRE></UL>
<BR>
<HR>
<A HREF="13-6.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-8.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,88 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The for_each() Algorithm</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13-7.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>13.8 The for_each() Algorithm</H2>
<A NAME="idx343"><!></A>
<P>The algorithm <SAMP>std::for_each()</SAMP> applies a function to all elements in a collection. This algorithm takes three arguments: the first two provide the <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s that describe the sequence to be evaluated, and the third is a one-argument function. The algorithm <SAMP>std::for_each()</SAMP> applies the function to each value of the sequence, passing the value as an argument:</P>
<UL><PRE>
namespace std {
Function for_each(InputIterator first,
InputIterator last, Function);
}
</PRE></UL>
<P>For example, the following code fragment, which uses the <SAMP>print_if_leap()</SAMP> function, prints a list of the leap years that occur between 1900 and 1997: </P>
<UL><PRE>
std::cout &lt;&lt; "leap years between 1990 and 1997 are: ";
std::for_each(1990, 1997, print_if_leap);
std::cout &lt;&lt; std::endl;
</PRE></UL>
<P>The argument function is guaranteed to be invoked only once for each element in the sequence. The <SAMP>std::for_each()</SAMP> algorithm itself returns the value of the third argument, although this is usually ignored.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The function passed as the third argument is not permitted to make any modifications to the sequence, so it can only achieve a result by means of a side effect, such as printing, assigning a value to a global or static variable, or invoking another function that produces a side effect. If the argument function returns any result, it is ignored.
</B><HR></BLOCKQUOTE>
<P>The following example searches an array of <SAMP>int</SAMP> values representing dates, to determine which vintage wine years were also leap years:</P>
<UL><PRE>
int vintageYears[] = {1947, 1955, 1960, 1967, 1994};
...
std::cout &lt;&lt; "vintage years which were also leap years are: ";
std::for_each(vintageYears, vintageYears + 5, print_if_leap);
std::cout &lt;&lt; std::endl;
</PRE></UL>
<P>Side effects need not be restricted to printing. Assume we have a function <SAMP>countCaps()</SAMP> that counts the occurrence of capital letters:</P>
<UL><PRE>
int capCount = 0;
void countCaps(char c) { if (std::isupper(c)) capCount++; }
</PRE></UL>
<P>The following example counts the number of capital letters in a string value:</P>
<UL><PRE>
std::string advice = "Never Trust Anybody Over 30!";
std::for_each(advice.begin(), advice.end(),countCaps);
std::cout &lt;&lt; "upper-case letter count is "
&lt;&lt; capCount &lt;&lt; std::endl;
</PRE></UL>
<BR>
<HR>
<A HREF="13-7.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,83 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Generic Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="IV.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 13: Generic Algorithms</H1>
<UL>
<UL><LI><A HREF="13-1.html">13.1 Overview</A></LI></UL>
<UL><UL><LI><A HREF="13-1.html#1311">13.1.1 Include Files</A></LI></UL></UL>
<UL><LI><A HREF="13-2.html">13.2 Initialization Algorithms</A></LI></UL>
<UL><UL><LI><A HREF="13-2.html#1321">13.2.1 Fill a Sequence with An Initial Value</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-2.html#1322">13.2.2 Copy One Sequence Into Another Sequence</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-2.html#1323">13.2.3 Initialize a Sequence with Generated Values</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-2.html#1324">13.2.4 Swap Values from Two Parallel Ranges</A></LI></UL></UL>
<UL><LI><A HREF="13-3.html">13.3 Searching Operations</A></LI></UL>
<UL><UL><LI><A HREF="13-3.html#1331">13.3.1 Find an Element Satisfying a Condition</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-3.html#1332">13.3.2 Find Consecutive Duplicate Elements</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-3.html#1333">13.3.3 Find the First Occurrence of Any Value from a Sequence</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-3.html#1334">13.3.4 Find a Sub-Sequence within a Sequence</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-3.html#1335">13.3.5 Find the Last Occurrence of a Sub-Sequence</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-3.html#1336">13.3.6 Locate Maximum or Minimum Element</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-3.html#1337">13.3.7 Locate the First Mismatched Elements in Parallel Sequences</A></LI></UL></UL>
<UL><LI><A HREF="13-4.html">13.4 In-Place Transformations</A></LI></UL>
<UL><UL><LI><A HREF="13-4.html#1341">13.4.1 Reverse Elements in a Sequence</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-4.html#1342">13.4.2 Replace Certain Elements With Fixed Value</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-4.html#1343">13.4.3 Rotate Elements Around a Midpoint</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-4.html#1344">13.4.4 Partition a Sequence into Two Groups</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-4.html#1345">13.4.5 Generate Permutations in Sequence</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-4.html#1346">13.4.6 Merge Two Adjacent Sequences into One</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-4.html#1347">13.4.7 Randomly Rearrange Elements in a Sequence</A></LI></UL></UL>
<UL><LI><A HREF="13-5.html">13.5 Removal Algorithms</A></LI></UL>
<UL><UL><LI><A HREF="13-5.html#1351">13.5.1 Remove Unwanted Elements</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-5.html#1352">13.5.2 Remove Runs of Similar Values</A></LI></UL></UL>
<UL><LI><A HREF="13-6.html">13.6 Scalar-Producing Algorithms</A></LI></UL>
<UL><UL><LI><A HREF="13-6.html#1361">13.6.1 Count the Number of Elements That Satisfy a Condition</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-6.html#1362">13.6.2 Reduce Sequence to a Single Value</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-6.html#1363">13.6.3 Generalized Inner Product</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-6.html#1364">13.6.4 Test Two Sequences for Pairwise Equality</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-6.html#1365">13.6.5 Lexical Comparison</A></LI></UL></UL>
<UL><LI><A HREF="13-7.html">13.7 Sequence-Generating Algorithms</A></LI></UL>
<UL><UL><LI><A HREF="13-7.html#1371">13.7.1 Transform One or Two Sequences</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-7.html#1372">13.7.2 Partial Sums</A></LI></UL></UL>
<UL><UL><LI><A HREF="13-7.html#1373">13.7.3 Adjacent Differences</A></LI></UL></UL>
<UL><LI><A HREF="13-8.html">13.8 The for_each() Algorithm</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="IV.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="13-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,138 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="14.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>14.1 Overview</H2>
<A NAME="idx344"><!></A>
<P>In this section we describe the generic algorithms in the C++ Standard Library that are specific to ordered collections. These algorithms are summarized in <A HREF="14-1.html#Table&nbsp;20">Table&nbsp;20</A>:</P>
<H4><A NAME="Table&nbsp;20">Table&nbsp;20: Generic algorithms specific to ordered collections&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Algorithm</B>
</td><td valign=top><B>Purpose</B>
</td></tr>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Sorting algorithms</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>partial_sort()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Sorts only part of sequence</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>partial_sort_copy()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Partial sorts into copy</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>sort()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Rearranges sequence, places in order</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>stable_sort()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Sorts, retaining original order of equal elements</P>
</td></tr>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Nth largest element algorithm</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>nth_element()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Locates nth largest element</P>
</td></tr>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Binary search algorithms</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>binary_search()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Searches, returning a boolean value</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>equal_range()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Searches, returning both positions</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>lower_bound()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Searches, returning first position</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>upper_bound()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Searches, returning last position</P>
</td></tr>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Merge ordered sequences algorithm</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>merge()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Combines two ordered sequences</P>
</td></tr>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Set operations algoithms</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>includes()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Compares two sorted sequences and returns <SAMP>true</SAMP> if every element in the range [first2, last2) is contained in the range [first1, last1)</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>set_intersection()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Forms intersection of two sets</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>set_difference()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Forms difference of two sets</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>set_symmetric_difference()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Forms symmetric difference of two sets</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>set_union()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Forms union of two sets</P>
</td></tr>
<tr><td valign=top colspan=2 rowspan=1><P CLASS="TABLE"><B><I>Heap operations algorithms</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>make_heap()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Turns a sequence into a heap</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>push_heap()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Adds a new value to the heap</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>pop_heap()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Removes largest value from the heap</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>sort_heap()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Turns heap into sorted collection</P>
</td></tr>
</TABLE>
<P>Ordered collections can be created using the C++ Standard Library in a variety of ways. For example:</P>
<UL>
<LI><P CLASS="LIST">The containers <B><I><A HREF="../stdlibref/set.html">set</A></I></B>, <B><I><A HREF="../stdlibref/multiset.html">multiset</A></I></B>, <B><I><A HREF="../stdlibref/map.html">map</A></I></B>, and <B><I><A HREF="../stdlibref/multimap.html">multimap</A></I></B> are ordered collections by definition.</P></LI>
<LI><P CLASS="LIST">A <B><I><A HREF="../stdlibref/list.html">list</A></I></B> can be ordered by invoking the <SAMP>std::sort()</SAMP> member function.</P></LI>
<LI><P CLASS="LIST">A <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>, <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>, or ordinary C++ array can be ordered by using one of the sorting algorithms described in <A HREF="14-2.html">Section&nbsp;14.2</A>.</P></LI>
</UL>
<P>Like the generic algorithms described in <A HREF="13.html">Section&nbsp;13</A>, the algorithms described here are not specific to any particular container class. This means that they can be used with a wide variety of types. However, many of them do require the use of random-access <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s. For this reason they are most easily used with <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>s, <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>s, or ordinary arrays.</P>
<P>Almost all the algorithms described in this section have two versions. The first version uses <SAMP>operator&lt;()</SAMP> for comparisons appropriate to the container element type. The second, and more general, version uses an explicit comparison function object, which we will write as <SAMP>Compare</SAMP>. This function object must be a binary predicate (see <A HREF="3-3.html">Section&nbsp;3.3</A>). Since this argument is optional, we will write it within square brackets in the description of the argument types.</P>
<A NAME="idx345"><!></A>
<P>A sequence is considered <I>ordered</I> if for every valid or <I>denotable</I> iterator <SAMP>i</SAMP> with a denotable successor <SAMP>j</SAMP>, the comparison <SAMP>Compare(*j, *i)</SAMP> is <SAMP>false</SAMP>. Note that this does not necessarily imply that <SAMP>Compare(*i, *j)</SAMP> is <SAMP>true</SAMP>. It is assumed that the relation imposed by <SAMP>Compare</SAMP> is transitive, and induces a total ordering on the values.</P>
<P>In the descriptions that follow, two values <SAMP>x</SAMP> and <SAMP>y</SAMP> are said to be equivalent if both <SAMP>Compare(x, y)</SAMP> and <SAMP>Compare(y, x)</SAMP> are <SAMP>false</SAMP>. Note that this need not imply that <SAMP>x == y</SAMP>.</P>
<A NAME="1411"><H3>14.1.1 Include Files</H3></A>
<A NAME="idx346"><!></A>
<P>As with the algorithms described in <A HREF="13.html">Chapter&nbsp;13</A>, before you can use any of these algorithms in a program you must include the <SAMP>algorithm</SAMP> header file:</P>
<UL><PRE>
#include &lt;algorithm&gt;
</PRE></UL>
<BR>
<HR>
<A HREF="14.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,139 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Sorting Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="14-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>14.2 Sorting Algorithms</H2>
<BLOCKQUOTE><HR><B>
NOTE -- The example programs described in the following sections have been combined and are included in the file alg7.cpp. As in Chapter13, we generally omit output statements from the descriptions of the programs provided here, although they are included in the complete versions.
</B><HR></BLOCKQUOTE>
<A NAME="idx347"><!></A>
<P>The C++ Standard Library provides two fundamental sorting algorithms, described as follows:</P>
<UL><PRE>
namespace std {
void sort(RandomAccessIterator first,
RandomAccessIterator last [, Compare ] );
void stable_sort(RandomAccessIterator first,
RandomAccessIterator last [, Compare ] );
}
</PRE></UL>
<A NAME="idx348"><!></A>
<P>The <SAMP>std::sort()</SAMP> algorithm is slightly faster, but it does not guarantee that equal elements in the original sequence retain their relative orderings in the final result. If order is important, the <SAMP>std::stable_sort()</SAMP> version should be used.</P>
<P>Because these algorithms require random access <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s, they can be used only with <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>s, <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>s, and ordinary C pointers. Note, however, that the <B><I><A HREF="../stdlibref/list.html">list</A></I></B> container provides its own <SAMP>sort()</SAMP> member function.</P>
<P>The comparison operator can be explicitly provided when the default operator <SAMP>&lt;</SAMP> is not appropriate. This is used in the example program to sort a <B><I><A HREF="../stdlibref/list.html">list</A></I></B> into descending, rather than ascending order. An alternative technique for sorting an entire collection in the inverse direction is to describe the sequence using reverse <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s.</P>
<BLOCKQUOTE><HR><B>
NOTE -- Another sorting algorithm is provided by the heap operations described in <A HREF="14-7.html">Section&nbsp;14.7</A>.
</B><HR></BLOCKQUOTE>
<P>The following example program illustrates the <SAMP>std::sort()</SAMP> algorithm being applied to a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>, and the <SAMP>std::sort()</SAMP> algorithm with an explicit comparison operator being used with a <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>.</P>
<A NAME="idx349"><!></A>
<UL><PRE>
void sort_example()
// illustrates the use of the sort algorithm
// see alg7.cpp for complete source code
{
// fill both a vector and a deque
// with random integers
std::vector&lt;int&gt; aVec(15);
std::deque&lt;int&gt; aDec(15);
std::generate(aVec.begin(), aVec.end(), randomValue);
std::generate(aDec.begin(), aDec.end(), randomValue);
// sort the vector ascending
std::sort(aVec.begin(), aVec.end());
// sort the deque descending
std::sort(aDec.begin(), aDec.end(), greater&lt;int&gt;() );
// alternative way to sort descending
std::sort(aVec.rbegin(), aVec.rend());
}
</PRE></UL>
<A NAME="1421"><H3>14.2.1 Partial Sort</H3></A>
<A NAME="idx350"><!></A>
<P>The generic algorithm <SAMP>std::partial_sort()</SAMP> sorts only a portion of a sequence. In the first version of the algorithm, three iterators are used to describe the beginning, middle, and end of a sequence. If <SAMP>n</SAMP> represents the number of elements between the start and middle, then the smallest <SAMP>n</SAMP> elements are moved into this range in order. The remaining elements are moved into the second region. The order of the elements in this second region is undefined.</P>
<UL><PRE>
namespace std {
void partial_sort(RandomAccessIterator first,
RandomAccessIterator middle,
RandomAccessIterator last
[ , Compare ]);
}
</PRE></UL>
<P>A second version of the algorithm leaves the input unchanged. The output area is described by a pair of random access <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s. If <SAMP>n</SAMP> represents the size of this area, the smallest <SAMP>n</SAMP> elements in the input are moved into the output in order. If <SAMP>n</SAMP> is larger than the input, the entire input is sorted and placed in the first <SAMP>n</SAMP> locations in the output. In either case, the end of the output sequence is returned as the result of the operation.</P>
<UL><PRE>
namespace std {
RandomAccessIterator partial_sort_copy
(InputIterator first, InputIterator last,
RandomAccessIterator result_first,
RandomAccessIterator result_last [, Compare ] );
}
</PRE></UL>
<A NAME="idx351"><!></A>
<P>Because the input to this version of the algorithm is specified only as a pair of input iterators, the <SAMP>std::partial_sort_copy()</SAMP> algorithm can be used with any of the containers in the C++ Standard Library. In the example program, it is used with a <B><I><A HREF="../stdlibref/list.html">list</A></I></B>:</P>
<A NAME="idx352"><!></A>
<UL><PRE>
void partial_sort_example()
// illustrates the use of the partial sort algorithm
// see alg7.cpp for complete source code
{
// make a vector of 15 random integers
std::vector&lt;int&gt; aVec(15);
std::generate(aVec.begin(), aVec.end(), randomValue);
// partial sort the first seven positions
std::partial_sort(aVec.begin(), aVec.begin() + 7, aVec.end());
// make a list of random integers
std::list&lt;int&gt; aList(15, 0);
std::generate(aList.begin(), aList.end(), randomValue);
// sort only the first seven elements
std::vector&lt;int&gt; start(7);
std::partial_sort_copy(aList.begin(), aList.end(),
start.begin(), start.end(),
std::greater&lt;int&gt;());
}
</PRE></UL>
<BR>
<HR>
<A HREF="14-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,82 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>nth Element</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="14-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>14.3 nth Element</H2>
<A NAME="idx353"><!></A>
<A NAME="idx354"><!></A>
<P>Imagine we have the sequence <SAMP>2 5 3 4 7</SAMP>, and we want to discover the median or middle element. If we do this with the function <SAMP>std::nth_element()</SAMP>, one result might be the following sequence:</P>
<UL><PRE>
3 2 | 4 | 7 5
</PRE></UL>
<P>The vertical bars are used to describe the separation of the result into three parts: the elements before the requested value, the requested value, and the values after the requested value. Note that the values in the first and third sequences are unordered; in fact, they can appear in the result in any order. The only requirement is that the values in the first part are no larger than the value we are seeking, and the elements in the third part are no smaller than this value.</P>
<P>The three iterators provided as arguments to the algorithm <SAMP>std::nth_element()</SAMP> divide the argument sequence into the three sections we just described. These are the section prior to the middle iterator, the single value denoted by the middle iterator, and the region between the middle iterator and the end. Either the first or third of these may be empty.</P>
<P>The arguments to the algorithm can be described as follows:</P>
<UL><PRE>
namespace std {
void nth_element(RandomAccessIterator first,
RandomAccessIterator nth,
RandomAccessIterator last
[, Compare ] );
}
</PRE></UL>
<P>Following the call on <SAMP>std::nth_element()</SAMP>, the nth largest value is copied into the position denoted by the middle <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>. The region between the first <B><I>iterator</I></B> and the middle iterator will have values no larger than the nth element, while the region between the middle <B><I>iterator</I></B> and the end will hold values no smaller than the nth element.</P>
<P>The example program illustrates finding the fifth largest value in a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> of random numbers.</P>
<A NAME="idx355"><!></A>
<UL><PRE>
void nth_element_example()
// illustrates the use of the nth_element algorithm
// see alg7.cpp for complete source code
{
// make a vector of random integers
std::vector&lt;int&gt; aVec(10);
std::generate(aVec.begin(), aVec.end(), randomValue);
// now find the 5th largest
std::vector&lt;int&gt;::iterator nth = aVec.begin() + 4;
std::nth_element(aVec.begin(), nth, aVec.end());
std::cout &lt;&lt; "fifth largest is " &lt;&lt; *nth &lt;&lt; std::endl;
}
</PRE></UL>
<BR>
<HR>
<A HREF="14-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,99 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Binary Search</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="14-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-5.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>14.4 Binary Search</H2>
<A NAME="idx356"><!></A>
<P>The C++ Standard Library provides a number of different variations on binary search algorithms. All perform only approximately <SAMP>log N</SAMP> comparisons, where <SAMP>N</SAMP> is the number of elements in the range described by the arguments. The algorithms work best with random access <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s, such as those generated by <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>s or <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>s. In this case they perform approximately <SAMP>log N</SAMP> operations in total. However, these algorithms also work with non-random access <B><I>iterator</I></B>s, such as those generated by <B><I><A HREF="../stdlibref/list.html">list</A></I></B>s, in which case they perform a linear number of steps. Although possible, it is not worthwhile to perform a binary search on a <B><I><A HREF="../stdlibref/set.html">set</A></I></B> or <B><I><A HREF="../stdlibref/multiset.html">multiset</A></I></B> data structure, since those container classes provide their own search methods, which are more efficient.</P>
<A NAME="idx357"><!></A>
<P>The generic algorithm <SAMP>std::binary_search()</SAMP> returns <SAMP>true</SAMP> if the sequence contains a value that is equivalent to the argument. Recall that to be equivalent means that both <SAMP>Compare(value, arg)</SAMP> and <SAMP>Compare(arg, value)</SAMP> are <SAMP>false</SAMP>. The algorithm is declared as follows:</P>
<UL><PRE>
namespace std {
bool binary_search(ForwardIterator first, ForwardIterator last,
const T&amp; value [, Compare ] );
}
</PRE></UL>
<P>In other situations it is important to know the position of the matching value. This information is returned by a collection of algorithms, defined as follows:</P>
<UL><PRE>
namespace std {
ForwardIterator lower_bound(ForwardIterator first,
ForwardIterator last, const T&amp; value [, Compare ] );
ForwardIterator upper_bound (ForwardIterator first,
ForwardIterator last, const T&amp; value [, Compare ] );
pair&lt;ForwardIterator, ForwardIterator&gt; equal_range
(ForwardIterator first, ForwardIterator last,
const T&amp; value [, Compare ] );
}
</PRE></UL>
<A NAME="idx358"><!></A>
<P>The algorithm <SAMP>std::lower_bound()</SAMP> returns, as an <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>, the first position into which the argument could be inserted without violating the ordering, whereas the algorithm <SAMP>std::upper_bound()</SAMP> finds the last such position. These match only when the element is not currently found in the sequence. Both can be executed together in the algorithm <SAMP>std::equal_range()</SAMP>, which returns a pair of <B><I>iterator</I></B>s.</P>
<P>Our example program shows these functions being used with a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> of random integers.</P>
<A NAME="idx359"><!></A>
<UL><PRE>
void binary_search_example()
// illustrates the use of the binary search algorithm
// see alg7.cpp for complete source code
{
// make an ordered vector of 15 random integers
std::vector&lt;int&gt; aVec(15);
std::generate(aVec.begin(), aVec.end(), randomValue);
std::sort(aVec.begin(), aVec.end());
// see if it contains an eleven
if (binary_search(aVec.begin(), aVec.end(), 11))
std::cout &lt;&lt; "contains an 11" &lt;&lt; std::endl;
else
std::cout &lt;&lt; "does not contain an 11" &lt;&lt; std::endl;
// insert an 11 and a 14
std::vector&lt;int&gt;::iterator where;
where = std::lower_bound(aVec.begin(), aVec.end(), 11);
aVec.insert(where, 11);
where = std::upper_bound(aVec.begin(), aVec.end(), 14);
aVec.insert(where, 14);
}
</PRE></UL>
<BR>
<HR>
<A HREF="14-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-5.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,90 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Merge Ordered Sequences</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="14-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-6.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>14.5 Merge Ordered Sequences</H2>
<A NAME="idx360"><!></A>
<P>The algorithm <SAMP>std::merge()</SAMP> combines two ordered sequences to form a new ordered sequence. The size of the result is the sum of the sizes of the two argument sequences. This should be contrasted with the <SAMP>std::set_union()</SAMP> operation, which eliminates elements that are duplicated in both sets. The <SAMP>std::set_union()</SAMP> function is described later in this chapter.</P>
<P>The merge operation is stable. This means, for equal elements in the two ranges, not only is the relative ordering of values from each range preserved, but the values from the first range always precede the elements from the second. The two ranges are described by a pair of <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s, whereas the result is defined by a single output <B><I>iterator</I></B>. The arguments are shown in the following declaration:</P>
<UL><PRE>
namespace std {
OutputIterator merge
(InputIterator first1, InputIterator last1,
InputIterator first2, InputIterator last2,
OutputIterator result [, Compare ]);
}
</PRE></UL>
<P>The example program illustrates a simple merge, the use of a merge with an inserter, and the use of a merge with an output stream <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>.</P>
<A NAME="idx361"><!></A>
<UL><PRE>
void merge_example()
// illustrates the use of the merge algorithm
// see alg7.cpp for complete source code
{
// make a list and vector of 10 random integers
std::vector&lt;int&gt; aVec(10);
std::list&lt;int&gt; aList(10, 0);
std::generate(aVec.begin(), aVec.end(), randomValue);
std::sort(aVec.begin(), aVec.end());
std::generate_n(aList.begin(), 10, randomValue);
aList.sort();
// merge into a vector
std::vector&lt;int&gt; vResult(aVec.size() + aList.size());
std::merge(aVec.begin(), aVec.end(),
aList.begin(), aList.end(), vResult.begin());
// merge into a list
std::list&lt;int&gt; lResult;
std::merge(aVec.begin(), aVec.end(), aList.begin(),
aList.end(), inserter(lResult, lResult.begin()));
// merge into the output
std::merge(aVec.begin(), aVec.end(), aList.begin(), aList.end(),
std::ostream_iterator&lt;int,char&gt; (std::cout, " "));
std::cout &lt;&lt; std::endl;
}
</PRE></UL>
<A NAME="idx362"><!></A>
<P>The algorithm <SAMP>std::inplace_merge()</SAMP> (<A HREF="13-4.html#1346">Section&nbsp;13.4.6</A>) can be used to merge two sections of a single sequence into one sequence.</P>
<BR>
<HR>
<A HREF="14-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-6.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,106 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>set Operations</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="14-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-7.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>14.6 set Operations</H2>
<A NAME="idx363"><!></A>
<P>The operations of <SAMP>set_union</SAMP>, <SAMP>set_intersection</SAMP>, and <SAMP>set_difference</SAMP> were all described in <A HREF="8-2.html#827">Section&nbsp;8.2.7</A> when we discussed the <B><I><A HREF="../stdlibref/set.html">set</A></I></B> container class. However, the algorithms that implement these operations are generic, and applicable to any ordered data structure. The algorithms assume the input ranges are ordered collections that represent <B><I><A HREF="../stdlibref/multiset.html">multiset</A></I></B>s; that is, elements can be repeated. However, if the inputs represent <B><I>set</I></B>s, then the result will always be a <B><I>set</I></B>. Unlike the <SAMP>std::merge()</SAMP> algorithm, none of the <B><I>set</I></B> algorithms produce repeated elements in the output that are not present in the input <B><I>set</I></B>s.</P>
<P>The <B><I><A HREF="../stdlibref/set.html">set</A></I></B> operations all have the same format. The two input <B><I>set</I></B>s are specified by pairs of input <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s. The output <B><I>set</I></B> is specified by an input <B><I>iterator</I></B>, and the end of this range is returned as the result value. An optional comparison operator is the final argument. In all cases it is required that the output sequence not overlap in any manner with either of the input sequences.</P>
<UL><PRE>
namespace std {
OutputIterator set_union
(InputIterator first1, InputIterator last1,
InputIterator first2, InputIterator last2,
OutputIterator result [, Compare ] );
}
</PRE></UL>
<A NAME="idx364"><!></A>
<P>The example program illustrates the use of the four <B><I><A HREF="../stdlibref/set.html">set</A></I></B> algorithms, <SAMP> std::set_union()</SAMP>, <SAMP>std::set_intersection()</SAMP>, <SAMP>std::set_difference(),</SAMP> and <SAMP>std::set_symmetric_difference()</SAMP>. It also shows a call on <SAMP>std::merge()</SAMP> in order to contrast the merge and the set union operations. The algorithm <SAMP>std::includes()</SAMP> is slightly different. Again the two input sets are specified by pairs of input <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s, and the comparison operator is an optional fifth argument. The return value for the algorithm is <SAMP>true</SAMP> if the first <B><I>set</I></B> is entirely included in the second, and <SAMP>false</SAMP> otherwise.</P>
<A NAME="idx365"><!></A>
<UL><PRE>
void set_example()
// illustrates the use of the generic set algorithms
// see alg7.cpp for complete source code
{
std::ostream_iterator&lt;int&gt; intOut(cout, " ");
// make a couple of ordered lists
std::list&lt;int&gt; listOne, listTwo;
std::generate_n(std::inserter(listOne, listOne.begin()), 5,
iotaGen(1));
std::generate_n(std::inserter(listTwo, listTwo.begin()), 5,
iotaGen(3));
// now do the set operations
// union - 1 2 3 4 5 6 7
std::set_union(listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut);
std::cout &lt;&lt; std::endl;
// merge - 1 2 3 3 4 4 5 5 6 7
std::merge(listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut);
std::cout &lt;&lt; std::endl;
// intersection - 3 4 5
std::set_intersection(listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut);
std::cout &lt;&lt; std::endl;
// difference - 1 2
std::set_difference(listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut);
std::cout &lt;&lt; std::endl;
// symmetric difference - 1 2 6 7
std::set_symmetric_difference(listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(),
intOut);
std::cout &lt;&lt; std::endl;
if (std::includes(listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end()))
std::cout &lt;&lt; "set is subset" &lt;&lt; std::endl;
else
std::cout &lt;&lt; "set is not subset" &lt;&lt; std::endl;
}
</PRE></UL>
<BR>
<HR>
<A HREF="14-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-7.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,115 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>heap Operations</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="14-6.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="V.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>14.7 heap Operations</H2>
<A NAME="idx366"><!></A>
<P>A <I>heap</I> is a binary tree in which every node is larger than the values associated with either child. A heap and a binary tree, for that matter, can be very efficiently stored in a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>, by placing the children of node<SAMP> i</SAMP> in positions <SAMP>2 * i + 1</SAMP> and <SAMP>2 * i + 2</SAMP>.</P>
<P>Using this encoding, the largest value in the heap is always located in the initial position, and can therefore be very efficiently retrieved. In addition, efficient logarithmic algorithms exist that permit a new element to be added to a heap and the largest element removed from a heap. For these reasons, a heap is a natural representation for the <B><I>priority queue</I></B> datatype, described in <A HREF="11.html">Chapter&nbsp;11</A>.</P>
<P>The default operator is the less-than operator <SAMP>&lt;</SAMP> appropriate to the element type. If desired, an alternative operator can be specified. For example, by using the greater-than operator <SAMP>&gt;</SAMP>, one can construct a heap that locates the smallest element in the first location, instead of the largest.</P>
<A NAME="idx367"><!></A>
<P>The algorithm <SAMP>std::make_heap()</SAMP> takes a range, specified by random access <B><I><A HREF="../stdlibref/iterator.html">iterator</A></I></B>s, and converts it into a heap. The number of steps required is a linear function of the number of elements in the range.</P>
<UL><PRE>
namespace std {
void make_heap(RandomAccessIterator first,
RandomAccessIterator last [, Compare ]);
}
</PRE></UL>
<A NAME="idx368"><!></A>
<P>To add a new element to a heap, insert it at the end of a range using the <SAMP>std::push_back()</SAMP> member function of a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> or <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>, for example, and invoke the algorithm <SAMP>std::push_heap()</SAMP>. The <SAMP>std::push_heap()</SAMP> algorithm restores the heap property, performing at most a logarithmic number of operations.</P>
<UL><PRE>
namespace std {
void push_heap(RandomAccessIterator first,
RandomAccessIterator last [, Compare ]);
}
</PRE></UL>
<A NAME="idx369"><!></A>
<P>The algorithm <SAMP>std::pop_heap()</SAMP> swaps the first and final elements in a range, and restores to a heap the collection without the final element. The largest value of the original collection is therefore still available as the last element in the range. It can be accessed using the <SAMP>back()</SAMP> member function in a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>, for example, and removed using the <SAMP>pop_back()</SAMP> member function. At the same time, the remainder of the collection continues to have the heap property. The <SAMP>std::pop_heap()</SAMP> algorithm performs at most a logarithmic number of operations.</P>
<UL><PRE>
namespace std {
void pop_heap(RandomAccessIterator first,
RandomAccessIterator last [, Compare ]);
}
</PRE></UL>
<A NAME="idx370"><!></A>
<P>Finally, the algorithm <SAMP>std::sort_heap()</SAMP> converts a heap into an ordered or <I>sorted</I> collection. Note that a sorted collection is still a heap, although the reverse is not the case. </P>
<BLOCKQUOTE><HR><B>
NOTE -- An ordered collection is a heap, but a heap need not necessarily be an ordered collection. In fact, a heap can be constructed in a sequence much more quickly than the sequence can be sorted.
</B><HR></BLOCKQUOTE>
<P>The sort is performed using approximately <SAMP>N log N</SAMP> operations, where <SAMP>N</SAMP> represents the number of elements in the range. The <SAMP>std::sort_heap()</SAMP> algorithm is not stable. Equal elements are not guaranteed to retain their relative pre-sort order.</P>
<UL><PRE>
namespace std {
void sort_heap(RandomAccessIterator first,
RandomAccessIterator last [, Compare ]);
}
</PRE></UL>
<P>Here is an example program that illustrates the use of these functions:</P>
<A NAME="idx371"><!></A>
<UL><PRE>
void heap_example()
// illustrates the use of the heap algorithms
// see alg7.cpp for complete source code
{
// make a heap of 15 random integers
std::vector&lt;int&gt; aVec(15);
std::generate(aVec.begin(), aVec.end(), randomValue);
std::make_heap(aVec.begin(), aVec.end());
std::cout &lt;&lt; "Largest value " &lt;&lt; aVec.front() &lt;&lt; std::endl;
// remove largest and reheap
std::pop_heap(aVec.begin(), aVec.end());
aVec.pop_back();
// add a 97 to the heap
aVec.push_back (97);
std::push_heap(aVec.begin(), aVec.end());
// finally, make into a sorted collection
std::sort_heap(aVec.begin(), aVec.end());
}
</PRE></UL>
<BR>
<HR>
<A HREF="14-6.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="V.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,55 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Ordered Collection Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="13-8.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 14: Ordered Collection Algorithms</H1>
<UL>
<UL><LI><A HREF="14-1.html">14.1 Overview</A></LI></UL>
<UL><UL><LI><A HREF="14-1.html#1411">14.1.1 Include Files</A></LI></UL></UL>
<UL><LI><A HREF="14-2.html">14.2 Sorting Algorithms</A></LI></UL>
<UL><UL><LI><A HREF="14-2.html#1421">14.2.1 Partial Sort</A></LI></UL></UL>
<UL><LI><A HREF="14-3.html">14.3 nth Element</A></LI></UL>
<UL><LI><A HREF="14-4.html">14.4 Binary Search</A></LI></UL>
<UL><LI><A HREF="14-5.html">14.5 Merge Ordered Sequences</A></LI></UL>
<UL><LI><A HREF="14-6.html">14.6 set Operations</A></LI></UL>
<UL><LI><A HREF="14-7.html">14.7 heap Operations</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="13-8.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="14-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,57 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="15.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="15-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>15.1 Overview</H2>
<A NAME="idx372"><!></A>
<P>The Standard C++ allocator interface encapsulates the types and functions needed to manage the storage of data in a generic way. The interface provides:</P>
<UL>
<LI><P CLASS="LIST">pointer and reference types</P></LI>
<LI><P CLASS="LIST">the type of the difference between pointers</P></LI>
<LI><P CLASS="LIST">the type to describe the size of a block of storage</P></LI>
<LI><P CLASS="LIST">storage allocation and deallocation primitives</P></LI>
<LI><P CLASS="LIST">object construction and destruction primitives.</P></LI>
</UL>
<A NAME="idx373"><!></A>
<P>This allocator interface wraps the mechanism for managing data storage, and separates this mechanism from the classes and functions used to maintain associations between data elements. This eliminates the need to rewrite containers and algorithms to suit different storage mechanisms. The interface lets you encapsulate all the storage mechanism details in an allocator, then provide that allocator to an existing container when appropriate.</P>
<P>The C++ Standard Library provides a default allocator class, <B><I><A HREF="../stdlibref/allocator.html">allocator</A></I></B>, that implements this interface using the standard <SAMP>new</SAMP> and <SAMP>delete</SAMP> operators for all storage management. </P>
<A NAME="idx374"><!></A>
<P>This chapter briefly describes how to use <B><I><A HREF="../stdlibref/allocator.html">allocator</A></I></B>s with existing containers, then discusses what you need to consider when designing your own <B><I>allocator</I></B>s. <A HREF="16.html">Chapter&nbsp;16</A> describes what you must consider when designing containers that use <B><I>allocator</I></B>s.</P>
<BR>
<HR>
<A HREF="15.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="15-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,78 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Using Allocators with Existing C++ Standard Library Containers</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="15-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="15-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>15.2 Using Allocators with Existing C++ Standard Library Containers</H2>
<A NAME="idx375"><!></A>
<P>Using allocators with existing C++ Standard Library container classes is a simple process. You just provide an allocator type when you instantiate a container, and provide an actual allocator object when you construct a container object:</P>
<UL><PRE>
template &lt;class T&gt; class my_allocator {...}; // Define an allocator
my_allocator&lt;int&gt; alloc; // Construct instance
std::vector&lt;int,my_allocator&lt;int&gt; &gt; v(alloc);// Use the allocator
</PRE></UL>
<A NAME="idx376"><!></A>
<P>All standard containers have a default allocator template of type <SAMP>std::allocator&lt;T&gt; </SAMP>and a default allocator constructor argument of type <SAMP>allocator_type()</SAMP>, where <SAMP>allocator_type</SAMP> is a typedef for the allocator template parameter. This means that the simplest use of allocators is to ignore them entirely. When you do not specify an allocator, the default allocator is used for all storage management.</P>
<P>If you do provide a different allocator type as a template parameter, the type of the allocator argument passed to the container's constructor must either exactly match or be implicitly convertible to the allocator template parameter. For example, the following code will cause a compiler error because the types of the template parameter and the constructor argument don't match: </P>
<UL><PRE>
template &lt;class T&gt; class my_allocator {...};
std::list&lt;int,std::allocator&lt;int&gt; &gt;
my_list(my_allocator&lt;int&gt;()); // Wrong!
</PRE></UL>
<P>The following call to the allocator constructor does match the template signature:</P>
<UL><PRE>
std::list &lt;int,my_allocator&lt;int&gt; &gt; my_list(my_allocator&lt;int&gt;());
</PRE></UL>
<P>It's also important that the type used for the allocator template parameter and the type used as the element type in a standard container agree. For instance:</P>
<UL><PRE>
std::list&lt;int, std::allocator&lt;long&gt; &gt; // Wrong!
</PRE></UL>
<P>won't work. Remember that with a <B><I><A HREF="../stdlibref/map.html">map</A></I></B> the contained type is actually a key-value pair:</P>
<UL><PRE>
std::map&lt;int,long,std::less&lt;int&gt;,
std::allocator&lt;std::pair&lt;const int,long&gt; &gt; &gt;
</PRE></UL>
<P>Note that the container always holds a <I>copy</I> of the <B><I><A HREF="../stdlibref/allocator.html">allocator</A></I></B> object that is passed to the constructor. If you need a single <B><I>allocator</I></B> object to manage all storage for a number of containers, you must provide an <B><I>allocator</I></B> that maintains a reference to some shared implementation.</P>
<BR>
<HR>
<A HREF="15-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="15-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,145 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Building Your Own Allocators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="15-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>15.3 Building Your Own Allocators</H2>
<A NAME="idx377"><!></A>
<P>Defining your own <B><I><A HREF="../stdlibref/allocator.html">allocator</A></I></B> is a relatively simple process. The C++ Standard Library describes a particular interface, consisting of types and functions. An allocator that conforms to the standard must match the syntactic requirements for these member functions and types. The C++ Standard Library also specifies a portion of the semantics for the allocator type.</P>
<A NAME="1531"><H3>15.3.1 Using the Standard Allocator Interface</H3></A>
<A NAME="idx378"><!></A>
<P>An <B><I><A HREF="../stdlibref/allocator.html">allocator</A></I></B> that conforms to the C++ Standard Library allocator specification must have the following interface. The example uses <SAMP>my_allocator</SAMP> as a place holder for your own allocator name:</P>
<UL><PRE>
template &lt;class T&gt;
class my_allocator
{
typedef <I>unsigned integral type</I> size_type;
typedef <I>signed integral type</I> difference_type;
typedef <I>pointer to T</I> pointer;
typedef <I>const pointer to T</I> const_pointer;
typedef T&amp; reference;
typedef const T&amp; const_reference;
typedef T value_type;
template &lt;class U&gt;
struct rebind { typedef allocator&lt;U&gt; other; };
};
</PRE></UL>
<P>The rebind member allows a container to construct an allocator for some arbitrary type out of the allocator type provided as a template parameter. For instance, the <B><I><A HREF="../stdlibref/list.html">list</A></I></B> container gets an <B><I><A HREF="../stdlibref/allocator.html">allocator&lt;T&gt;</A></I></B> by default, but a <B><I>list</I></B> may well need to allocate <B><I>list_node</I></B>s as well as <B><I>T</I></B>'s. The container can construct an allocator for <B><I>list_node</I></B>s out of the allocator for <B><I>T</I></B>, which is the template parameter <B><I><A HREF="../stdlibref/allocator.html">Allocator</A></I></B> in this case, as follows:</P>
<UL><PRE>
Allocator::rebind&lt;list_node&gt;::other list_node_allocator;
</PRE></UL>
<A NAME="idx379"><!></A>
<P>Here is a description of the member functions that an <B><I><A HREF="../stdlibref/allocator.html">allocator</A></I></B> class template must provide:</P>
<A NAME="idx380"></A><PRE>
<B>my_allocator</B>();
template &lt;class U&gt;</PRE>
<UL>
</UL>
<A NAME="idx381"></A><PRE><B>my_allocator</B>(const my_allocator&lt;U&gt;&amp;);
template &lt;class U&gt;</PRE>
<UL>
<P>Constructors.</P>
</UL>
<A NAME="idx382"></A><PRE><B>~my_allocator</B>();</PRE>
<UL>
<P>Destructor.</P>
</UL>
<A NAME="idx383"></A><PRE><B>operator=</B>(const my_allocator&lt;U&gt;&amp;);</PRE>
<UL>
<P>Assignment operator.</P>
</UL>
<A NAME="idx384"></A><PRE><B>pointer address</B>(reference r) const;</PRE>
<UL>
<P>Returns the address of <SAMP>r</SAMP> as a <SAMP>pointer</SAMP> type. This function and the following function are used to convert references to pointers.</P>
</UL>
<A NAME="idx385"></A><PRE><B>const_pointer address</B>(const_reference r) const;</PRE>
<UL>
<P>Returns the address of <SAMP>r</SAMP> as a <SAMP>const_pointer</SAMP> type.</P>
</UL>
<A NAME="idx386"></A><PRE><B>pointer allocate</B>(size_type n, allocator&lt;U&gt;::const_pointer hint=0);</PRE>
<UL>
<P>Allocates storage for <SAMP>n</SAMP> values of<SAMP> T</SAMP>. Uses the value of <SAMP>hint</SAMP> to optimize storage placement, if possible.</P>
</UL>
<A NAME="idx387"></A><PRE>void
<B>deallocate</B>(pointer);</PRE>
<UL>
<P>Deallocates storage obtained by a call to <SAMP>allocate</SAMP>.</P>
</UL>
<A NAME="idx388"></A><PRE>size_type
<B>max_size</B>();</PRE>
<UL>
<P>Returns the largest possible storage available through a call to <SAMP>allocate</SAMP>.</P>
</UL>
<A NAME="idx389"></A><PRE>void
<B>construct</B>(pointer p, const_reference val);</PRE>
<UL>
<P>Constructs an object of type <SAMP>T</SAMP> at the location of <SAMP>p</SAMP>, using the value of <SAMP>val</SAMP> in the call to the constructor for <SAMP>T</SAMP>.</P>
</UL>
<A NAME="idx390"></A><PRE>void
<B>destroy</B>(pointer p);</PRE>
<UL>
<P>Calls the destructor on the value pointed to by <SAMP>p</SAMP>.</P>
</UL>
<P>Additionally, user-defined allocators must be equality comparable: if <SAMP>a</SAMP> and <SAMP>b</SAMP> are instances of a user-defined allocator, then the expressions <SAMP>(a == b)</SAMP> and <SAMP>(a != b)</SAMP> must be well-formed.</P>
<BR>
<HR>
<A HREF="15-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,50 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Using Allocators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="V.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="15-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 15: Using Allocators</H1>
<UL>
<UL><LI><A HREF="15-1.html">15.1 Overview</A></LI></UL>
<UL><LI><A HREF="15-2.html">15.2 Using Allocators with Existing C++ Standard Library Containers</A></LI></UL>
<UL><LI><A HREF="15-3.html">15.3 Building Your Own Allocators</A></LI></UL>
<UL><UL><LI><A HREF="15-3.html#1531">15.3.1 Using the Standard Allocator Interface</A></LI></UL></UL>
</UL>
<BR>
<HR>
<A HREF="V.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="15-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,58 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Extending the C++ Standard Library</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="16.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>16.1 Extending the C++ Standard Library</H2>
<A NAME="idx391"><!></A>
<A NAME="idx392"><!></A>
<P>The adoption of the C++ Standard Library marks a very important development for users of the C++ programming language. Although the library is written in an OO language and provides plenty of objects, it also employs an entirely different paradigm. This other approach, called <I>generic programming</I>, provides a flexible way to apply generic algorithms to a wide variety of different data structures. The flexibility of C++ in combination with this synthesis of two advanced design paradigms results in an unusual and highly-extensible library.</P>
<A NAME="idx393"><!></A>
<P>The clearest example of this synthesis is the ability to extend the C++ Standard Library with user-defined containers and algorithms. This extension is possible because the definition of data structures has been separated from the definition of generic operations on those structures (<A HREF="1-2.html#122">Section&nbsp;1.2.2</A>). The library defines very specific parameters for these two broad groups, giving users some confidence that containers and algorithms from different sources will work together as long as they all meet the specifications of the standard. At the same time, containers encapsulate data and a limited range of operations on that data in classic OOP fashion.</P>
<A NAME="idx394"><!></A>
<P>Each standard container is categorized as one of two types: a <I>sequence</I> or an <I>associative container</I>. A user-defined container need not fit into either of these two groups since the standard also defines rudimentary requirements for a container, but the categorization can be very useful for determining which algorithms will work with a particular container and how efficiently those algorithms will work. In determining the category of a container, the most important characteristics are the <I>iterator category</I> and <I>element ordering</I>. (See the chapter on each container type, and the listing for each container and iterator in the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A>.)</P>
<A NAME="idx395"><!></A>
<P>C++ Standard Library algorithms can be grouped into categories using a number of different criteria. The most important of these are: </P>
<UL>
<LI><P CLASS="LIST"> whether or not the algorithm modifies the contents of a container</P></LI>
<LI><P CLASS="LIST"> the type of iterator required by the algorithm</P></LI>
<LI><P CLASS="LIST">whether or not the algorithm requires a container to be sorted. </P></LI>
</UL>
<P>An algorithm may also require further state conditions from any container it's applied to. For instance, all the standard <B><I><A HREF="../stdlibref/set.html">set</A></I></B> algorithms require not only that a container is in sorted order, but also that the order of elements is determined using the same compare function or object that will be used by the algorithm.</P>
<BR>
<HR>
<A HREF="16.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,136 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Building on the Standard Containers</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="16-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>16.2 Building on the Standard Containers</H2>
<A NAME="idx396"><!></A>
<P>Let's examine a few of the ways you can use existing C++ Standard Library containers to create your own containers. For example, say you want to implement a <B><I><A HREF="../stdlibref/set.html">set</A></I></B> container that enforces unique values that are not inherently sorted. You also want a group of algorithms to operate on that <B><I>set</I></B>. The container is certainly a <I>sequence</I> but not an a<I>ssociative container</I>, since an associative container is sorted by definition. The algorithms will presumably work on other sequences, assuming those sequences provide appropriate iterator types, since the iterator required by a set of algorithms determines the range of containers those algorithms can be applied to. The algorithms will be universally available if they require only forward iterators. On the other hand, they'll be most restrictive if they require random access iterators.</P>
<A NAME="idx397"><!></A>
<P>Simple implementations of this <B><I><A HREF="../stdlibref/set.html">set</A></I></B> container could make use of existing C++ Standard Library containers for much of their mechanics. Three possible ways of achieving this code reuse are:</P>
<UL>
<LI><P CLASS="LIST">inheritance</P></LI>
<LI><P CLASS="LIST">generic inheritance</P></LI>
<LI><P CLASS="LIST">generic composition.</P></LI>
</UL>
<P>Let's take a look at each of these approaches in the next sections.</P>
<A NAME="idx398"><!></A>
<A NAME="1621"><H3>16.2.1 Inheritance</H3></A>
<A NAME="idx399"><!></A>
<P>As you recall, <I>inheritance</I> is the powerful feature of object-oriented programming that allows objects to derive attributes and behavior from other objects. To create your own container, you could derive from an existing Standard C++ container, then override certain functions to get the desired behavior. One approach would be to derive from the <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> container, as shown here:</P>
<UL><PRE>
#include &lt;vector&gt;
// note the use of a namespace to avoid conflicts with standard
// or global names
namespace my_namespace {
template &lt;class T, class Allocator = std::allocator&gt;
class set : public std::vector&lt;T,Allocator&gt; {
public:
// override functions such as insert
iterator insert(iterator position, const T&amp; x)
{
if (find(begin(),end(),x) == end())
return std::vector&lt;T,Allocator&gt;::insert(position,x);
else
return end(); // This value already present!
}
...
};
} // End of my_namespace
</PRE></UL>
<A NAME="idx400"><!></A>
<A NAME="1622"><H3>16.2.2 Generic Inheritance</H3></A>
<A NAME="idx401"><!></A>
<P>A second approach to creating your own container is to create a <I>generic adaptor</I>, rather than specifying <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>. You do this by providing the underlying container through a template parameter:</P>
<UL><PRE>
namespace my_namespace {
template &lt;class T, class Container = std::vector&lt;T&gt; &gt;
class set : public Container {
public:
// Provide typedefs (iterator only for illustration)
typedef typename Container::iterator iterator;
// override functions such as insert
iterator insert(iterator position, const T&amp; x) {
if (find(begin(),end(),x) == end())
return Container::insert(position,x);
else
return end(); // This value already present!
}
...
};
} // End of my_namespace
</PRE></UL>
<P>If you use generic inheritance through an adaptor, the adaptor and users of the adaptor cannot expect more than default capabilities and behavior from any container used to instantiate it. If the adaptor or its users expect functionality beyond what is required of a basic container, the documentation must specify precisely what is expected.</P>
<A NAME="1623"><H3>16.2.3 Generic Composition</H3></A>
<A NAME="idx402"><!></A>
<P>The third approach to building your own container uses <I>composition</I> rather than inheritance. You can see the spirit of this approach in the C++ Standard Library adaptors <B><I><A HREF="../stdlibref/queue.html">queue</A></I></B>, <B><I>priority queue</I></B>, and <B><I><A HREF="../stdlibref/stack.html">stack</A></I></B>. When you use generic composition, you have to implement all of the desired interface. This option is most useful when you want to limit the behavior of an adaptor by providing only a subset of the interface provided by the container.</P>
<UL><PRE>
namespace my_namespace {
template &lt;class T, class Container = std::vector&lt;T&gt; &gt;
class set
{
protected:
Container c;
public:
// Provide needed typedefs
typedef typename Container::iterator iterator;
// provide all necessary functions such as insert
iterator insert(iterator position, const T&amp; x)
{
if (find(c.begin(),c.end(),x) == c.end())
return c.insert(position,x);
else
return c.end(); // This value already present!
}
...
};
} // End of my_namespace
</PRE></UL>
<P>The advantages of adapting existing containers are numerous. For instance, you get to reuse the implementation and the specifications of the container that you're adapting.</P>
<BR>
<HR>
<A HREF="16-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,163 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Creating Your Own Containers</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="16-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>16.3 Creating Your Own Containers</H2>
<A NAME="idx403"><!></A>
<P>All of the options that build on existing C++ Standard Library containers incur a certain amount of overhead. When performance demands are critical, or the container requirements very specific, there may be no choice but to implement a container from scratch. </P>
<A NAME="idx404"><!></A>
<P>When building from scratch, there are three sets of design requirements that you must meet:</P>
<UL>
<LI><P CLASS="LIST">container interface requirements</P></LI>
<LI><P CLASS="LIST">allocator interface requirements</P></LI>
<LI><P CLASS="LIST">iterator requirements.</P></LI>
</UL>
<P>We'll talk about each of these in the next sections.</P>
<A NAME="1631"><H3>16.3.1 Meeting the Container Requirements</H3></A>
<A NAME="idx405"><!></A>
<P>The C++ Standard Library defines general interface requirements for containers, and specific requirements for specialized containers. When you create a container, the first part of your task is making sure that the basic interface requirements for a container are met. In addition, if your container will be a sequence or an associative container, you need to provide all additional pieces specified for those categories. For anything but the simplest container, this is definitely not a task for the faint of heart.</P>
<P>It's very important to meet the requirements so that users of the container will know exactly what capabilities to expect without having to read the code directly. Review the sections on individual containers for information about the container requirements. </P>
<A NAME="1632"><H3>16.3.2 Meeting the Allocator Interface Requirements</H3></A>
<A NAME="idx406"><!></A>
<P>A user-defined container makes use of the allocator interface for all storage management. An exception to this is a container that exists in a completely self-contained environment where there is no need for substitute allocators.</P>
<P>The basic interface of an <B><I><A HREF="../stdlibref/allocator.html">allocator</A></I></B> class consists of a set of typedefs, a pair of allocation functions, <SAMP>allocate()</SAMP> and <SAMP>deallocate()</SAMP>, and a pair of construction/destruction members, <SAMP>construct()</SAMP> and <SAMP>destroy()</SAMP>. The typedefs are used by a container to determine the look of pointers, references, sizes, and differences<I>,</I> where a <I>difference</I> means a distance between two pointers. The functions are used to do the actual management of data storage.</P>
<P>To use the allocator interface, a container must meet the following three requirements:</P>
<UL>
<LI><P CLASS="LIST">A container needs to have a set of typedefs that look like the following:</P></LI>
<UL><PRE>
typedef Allocator allocator_type;
typedef typename Allocator::size_type size_type;
typedef typename Allocator::difference_type difference_type;
typedef typename Allocator::reference reference;
typedef typename Allocator::const_reference const_reference;
typedef <I>implementation_defined</I> iterator;
typedef <I>implementation_defined</I> iterator;
</PRE></UL>
<LI><P CLASS="LIST">A container also needs to have an <SAMP>Allocator</SAMP> member that contains a copy of the allocator argument provided by the constructors:</P></LI>
<P CLASS="LIST"><SAMP>protected:<br> Allocator the_allocator;</SAMP></P>
<LI><P CLASS="LIST">A container needs to use that <SAMP>Allocator</SAMP> member for all storage management. For instance, our <B><I><A HREF="../stdlibref/set.html">set</A></I></B> container might have a naive implementation that simply allocates a large buffer and then constructs values on that buffer. Note that this not a very efficient mechanism, but it serves as a simple example. We're also going to avoid the issue of <SAMP>Allocator::allocate()</SAMP> throwing an exception, in the interest of brevity.</P></LI>
</UL>
<P>An abbreviated version of the <B><I><A HREF="../stdlibref/set.html">set</A></I></B> class appears below. The class interface shows the required typedefs and the <SAMP>Allocator</SAMP> member for this class:</P>
<UL><PRE>
#include &lt;memory&gt;
namespace my_namespace {
template &lt;class T, class Allocator = std::allocator&lt;T&gt; &gt;
class set
{
public:
// typedefs and allocator member as above
typedef Allocator allocator_type;
typedef typename Allocator::size_type size_type;
typedef typename Allocator::difference_type
difference_type;
typedef typename Allocator::reference reference;
typedef typename Allocator::const_reference
const_reference;
// Our iterator will be a simple pointer
typedef Allocator::pointer iterator;
typedef Allocator::const_pointer iterator;
protected:
Allocator the_allocator; // copy of the allocator
private:
size_type buffer_size;
iterator buffer_start;
iterator current_end;
iterator end_of_buffer;
public:
// A constructor that initializes the set using a range
// from some other container or array
template &lt;class Iterator&gt;
set(Iterator start, Iterator finish,
Allocator alloc = Allocator());
iterator begin() { return buffer_start; }
iterator end() { return current_end; }
};
</PRE></UL>
<P>Given this class interface, here's a definition of a possible constructor that uses the allocator. The numbered comments following this code briefly describe the allocator's role. For a more thorough treatment of allocators, see <A HREF="15.html">Chapter&nbsp;15</A> and the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A> entry for allocators.</P>
<UL><PRE>
template &lt;class T, class Allocator&gt;
template &lt;class Iterator&gt;
set&lt;T,Allocator&gt;::set(Iterator start, Iterator finish,
Allocator alloc)
: buffer_size(finish-start + DEFAULT_CUSHION),
buffer_start(0),
current_end(0), end_of_buffer(0)
{
// Copy the argument to our internal object
the_allocator = alloc; // 1
// Create an initial buffer
buffer_start = the_allocator.allocate(buffer_size); // 2
end_of_buffer = buffer_start + buffer_size;
// Construct new values from iterator range on the buffer
for (current_end = buffer_start;
start != finish;
current_end++, start++)
the_allocator.construct(current_end,*start); // 3
// Now let's remove duplicates using a standard algorithm
std::unique(begin(),end());
}
} // End of my_namespace
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>The allocator parameter is copied into a protected member of the container. This private copy can then be used for all subsequent storage management.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>An initial buffer is allocated using the allocator's allocate function.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>The contents of the buffer are initialized using the values from the iterator range supplied to the constructor by the <SAMP>start</SAMP> and <SAMP>finish</SAMP> parameters. The <SAMP>construct</SAMP> function constructs an object at a particular location. In this case the location is at an index in the container's buffer.
</TABLE>
<A NAME="1633"><H3>16.3.3 Iterator Requirements</H3></A>
<A NAME="idx407"><!></A>
<P>Every container must define an iterator type. Iterators allow algorithms to iterate over the container's contents. Although iterators can range from simple to very complex, it is not the complexity but the<I> iterator category</I> that most affects an algorithm. The iterator category describes capabilities of the iterator, such as which direction it can traverse. <A HREF="16-4.html">Section&nbsp;16.4</A> and the iterator entries in the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A> provide additional information about iterator categories.</P>
<P>The example in <A HREF="16-3.html#1632">Section&nbsp;16.3.2</A> shows the implementation of a container that uses a simple pointer. A simple pointer is actually an example of the most powerful type of iterator: the <I>random access iterator</I>. If an iterator supports random access, we can add to or subtract from it as easily as we can increment it.</P>
<P>Some iterators have much less capability. For example, consider an iterator attached to a singly-linked <I>list</I>. Since each node in the <B><I><A HREF="../stdlibref/list.html">list</A></I></B> has links leading forward only, a naive iterator can advance through the container in only one direction. An iterator with this limitation falls into the category of forward iterator. </P>
<P>Certain member functions such as <SAMP>begin()</SAMP> and <SAMP>end()</SAMP> produce iterators for a container. A container's description should always describe the category of iterator that its member functions produce. That way, a user of the container can see immediately which algorithms can operate successfully on the container.</P>
<BR>
<HR>
<A HREF="16-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,112 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Tips and Techniques for Building Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="16-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="17.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>16.4 Tips and Techniques for Building Algorithms</H2>
<A NAME="idx408"><!></A>
<P>This section describes some techniques that use features of iterators to increase the flexibility and efficiency of your algorithms.</P>
<A NAME="idx409"><!></A>
<A NAME="1641"><H3>16.4.1 The iterator_traits Template</H3></A>
<A NAME="idx410"><!></A>
<P>Sometimes an algorithm that can be implemented most efficiently with a random access iterator can also work with less powerful iterators. The C++ Standard Library includes primitives that allow a single algorithm to provide several different implementations, depending upon the power of the iterator passed into it. The following example demonstrates the usual technique for setting up multiple versions of the same algorithm:</P>
<UL><PRE>
// Note, this requires that the iterators be derived from
// Standard base types, unless the iterators are simple pointers.
namespace my_namespace {
template &lt;class Iterator&gt;
Iterator union(Iterator first1, Iterator last1,
Iterator first2, Iterator last2,
Iterator Result)
{
return union_aux(first1,last1,first2,last2,Result,
iterator_traits&lt;first1&gt;());
}
template &lt;class Iterator&gt;
Iterator union_aux(Iterator first1, Iterator last1,
Iterator first2, Iterator last2,
Iterator Result, forward_iterator_tag)
{
// General but less efficient implementation
}
template &lt;class Iterator&gt;
Iterator union_aux(Iterator first1, Iterator last1,
Iterator first2, Iterator last2,
Iterator Result,
random_access_iterator_tag)
{
// More efficient implementation
}
} // End of my_namespace
</PRE></UL>
<P>The <SAMP>iterator_traits</SAMP> template provides typedefs for value, difference, pointer, reference, and category types that are based on the type used to instantiate the template. In the example above, we use <SAMP>iterator_traits::iterator_category</SAMP> to determine the capabilities of the iterator, and then use specializations to get the best available implementation of the algorithm. In order for <SAMP>iterator_traits</SAMP> to work, the iterator provided to the algorithm must be a simple pointer type or be derived from the iterator template, or it must itself define the types for <SAMP>value_type</SAMP>, <SAMP>difference_type</SAMP>, <SAMP>pointer</SAMP>, <SAMP>reference</SAMP>, and <SAMP>iterator_category</SAMP>. The <SAMP>iterator_category</SAMP> type must be one of the following: <SAMP>input_iterator_tag</SAMP>, <SAMP>output_iterator_tag</SAMP>, <SAMP>forward_iterator_tag</SAMP>, <SAMP>bidirectional_iterator_tag</SAMP>, or <SAMP>random_access_iterator_tag</SAMP>.</P>
<P>Note that when you use the <SAMP>iterator_traits</SAMP> template, the default implementation of an algorithm should expect at most a forward iterator. This default version is used if the algorithm encounters an iterator that is not a simple pointer or derived from a basic standard iterator. Note that input and output iterators are less capable than forward iterators, but that the requirements of algorithms generally mandate read/write capabilities.</P>
<P>Not also that <SAMP>iterator_traits</SAMP> only works with compilers that support partial specialization, since the specialization of <SAMP>iterator_traits</SAMP> for pointer types uses this feature. If your compiler doesn't support partial specialization, you can use the primitive <SAMP>__iterator_category()</SAMP>. Calling this function with an iterator argument returns the same tag you would get by using <SAMP>iterator_traits</SAMP>. For example, we could substitute the following line for the use of <SAMP>iterator_traits</SAMP> in the previous example:</P>
<UL><PRE>
return std::union_aux(first1,last1,first2,last2,Result,
__iterator_category(first1));
</PRE></UL>
<P>Use <SAMP>iterator_traits::value_type</SAMP> and <SAMP>iterator_traits::difference_type</SAMP> to discover the type of value pointed to by an iterator, or the type that represents a distance between iterators. As with the category type, you must use the alternate functions <SAMP>__value_type()</SAMP> or <SAMP>__distance_type()</SAMP> when partial specialization is not available. Both of these functions take an iterator as an argument in just the same way as <SAMP>__iterator_category()</SAMP>.</P>
<A NAME="idx411"><!></A>
<A NAME="1642"><H3>16.4.2 The distance and advance Primitives</H3></A>
<A NAME="idx412"><!></A>
<P>The <SAMP>value_type</SAMP> primitive lets you determine the type of value pointed to by an iterator. Similarly, you can use the <SAMP>distance_type</SAMP> primitive to get a type that represents distances between iterators.</P>
<A NAME="idx413"><!></A>
<P>In order to efficiently find the distance between two iterators, regardless of their capabilities, you can use the <SAMP>distance</SAMP> primitive. The <SAMP>distance</SAMP> primitive uses the technique in <A HREF="16-4.html#1641">Section&nbsp;16.4.1</A> to send a calling program to one of four different implementations. This offers a considerable gain in efficiency, since an implementation for a forward iterator must step through the range defined by the two iterators:</P>
<UL><PRE>
Distance d = 0;
while (start++ != end)
d++;
</PRE></UL>
<P>whereas an implementation for a random access iterator can simply subtract the start iterator from the end iterator:</P>
<UL><PRE>
Distance d = end - start;
</PRE></UL>
<A NAME="idx414"><!></A>
<P>Similar gains are available with the <SAMP>advance</SAMP> primitive, which allows you to step forward or backward an arbitrary number of steps as efficiently as possible for a particular iterator.</P>
<BR>
<HR>
<A HREF="16-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="17.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,58 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Building Containers and Algorithms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="15-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 16: Building Containers and Algorithms</H1>
<UL>
<UL><LI><A HREF="16-1.html">16.1 Extending the C++ Standard Library</A></LI></UL>
<UL><LI><A HREF="16-2.html">16.2 Building on the Standard Containers</A></LI></UL>
<UL><UL><LI><A HREF="16-2.html#1621">16.2.1 Inheritance</A></LI></UL></UL>
<UL><UL><LI><A HREF="16-2.html#1622">16.2.2 Generic Inheritance</A></LI></UL></UL>
<UL><UL><LI><A HREF="16-2.html#1623">16.2.3 Generic Composition</A></LI></UL></UL>
<UL><LI><A HREF="16-3.html">16.3 Creating Your Own Containers</A></LI></UL>
<UL><UL><LI><A HREF="16-3.html#1631">16.3.1 Meeting the Container Requirements</A></LI></UL></UL>
<UL><UL><LI><A HREF="16-3.html#1632">16.3.2 Meeting the Allocator Interface Requirements</A></LI></UL></UL>
<UL><UL><LI><A HREF="16-3.html#1633">16.3.3 Iterator Requirements</A></LI></UL></UL>
<UL><LI><A HREF="16-4.html">16.4 Tips and Techniques for Building Algorithms</A></LI></UL>
<UL><UL><LI><A HREF="16-4.html#1641">16.4.1 The iterator_traits Template</A></LI></UL></UL>
<UL><UL><LI><A HREF="16-4.html#1642">16.4.2 The distance and advance Primitives</A></LI></UL></UL>
</UL>
<BR>
<HR>
<A HREF="15-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="16-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,47 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Defining the Problem</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="17.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="17-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>17.1 Defining the Problem</H2>
<P>The traits technique discussed in this chapter is useful for solving the following kind of problem. Consider that you have a matrix that must work for all types of numbers, but the behavior of the matrix depends on the type of number in at least some measure. This means your matrix can't handle all numbers the same way.</P>
<P>Except for the behavioral difference, it sounds like the perfect problem for a template. But you can't use a single template, since you can't hang extra information on the number type because it's often just a built-in type. The template will do the same thing for every number type, which is just what you can't do in this case. You could specialize, but then you have to re-implement the entire matrix class for every type of number. It may well be that most of the class is the same. Worse yet, if you want to leave your interface open for use with some unknown future type, you're requiring that future user to reimplement the entire class as well. </P>
<A NAME="idx415"><!></A>
<P>What you really want is to put everything that doesn't change in one place, and repeatedly specify only the small part that does change with the type. The technique for doing this is generally referred to as using a <I>traits</I> <I>parameter</I>.</P>
<BR>
<HR>
<A HREF="17.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="17-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,82 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Using the Traits Technique</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="17-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>17.2 Using the Traits Technique</H2>
<P>To implement a traits parameter for a class, you add it as an extra template parameter to your class. You then supply a class for this parameter that encapsulates all the specific operations. Usually that class is itself a template.</P>
<P>As an example, let's look at the matrix problem described in <A HREF="17-1.html">Section&nbsp;17.1</A>. When you want to add a new type to the matrix, you can use the traits technique and simply specialize the traits class, not the entire matrix. You do no more work than you have to, and you retain the ability to use the matrix on any reasonable number.</P>
<A NAME="idx416"><!></A>
<P>Here's how the matrix traits template and specializations for <SAMP>long</SAMP> and <SAMP>int</SAMP> might look. The example also includes a skeleton of the matrix class that uses the traits template.</P>
<UL><PRE>
template &lt;class Num&gt;
class matrix_traits
{
// traits functions and literals
};
template &lt;class Num, class traits&gt;
class matrix
{
// matrix
}
class matrix_traits&lt;long&gt;
{
// traits functions and literals specific to long
};
class matrix_traits&lt;int&gt;
{
// traits functions and literals specific to int
};
... etc.
std::matrix&lt;int, matrix_traits&lt;int&gt; &gt; int_matrix;
std::matrix&lt;long, matrix_traits&lt;long&gt; &gt; long_matrix;
</PRE></UL>
<P>Of course you don't even have to specialize on <SAMP>matrix_traits</SAMP>. You just have to make sure that you provide the interface that <SAMP>matrix</SAMP> expects from its traits template parameter. </P>
<A NAME="idx417"><!></A>
<P>Most of the time, the operations contained in a traits class are static functions so there's no need to actually instantiate a traits object.</P>
<A NAME="idx418"><!></A>
<P>The C++ Standard Library uses this technique to give the <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> class maximum flexibility and efficiency across a wide range of types. The <B><I><A HREF="../stdlibref/char-traits.html">char_traits</A></I></B> traits class provides elementary operations on character arrays. In the simplest case, this means providing <B><I>string</I></B> a <SAMP>wstring</SAMP> with access to the C library functions for narrow and wide characters, for example <SAMP>strcpy</SAMP> and <SAMP>wcstrcpy</SAMP>.</P>
<A NAME="idx419"><!></A>
<P>See the <B><I><A HREF="../stdlibref/char-traits.html">char_traits</A></I></B> entry in the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A> for a complete description of the traits class.</P>
<BR>
<HR>
<A HREF="17-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,48 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The Traits Parameter</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="16-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="17-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 17: The Traits Parameter</H1>
<UL>
<UL><LI><A HREF="17-1.html">17.1 Defining the Problem</A></LI></UL>
<UL><LI><A HREF="17-2.html">17.2 Using the Traits Technique</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="16-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="17-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,56 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="18.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>18.1 Overview</H2>
<A NAME="idx420"><!></A>
<P>The C++ Standard Library provides a set of classes for reporting errors. These classes use the exception handling facility of the language. The library implements a particular error model, which divides errors in two broad categories: <I>logic errors</I> and <I>runtime errors</I>.</P>
<A NAME="idx421"><!></A>
<P><I>Logic errors</I> are errors caused by problems in the internal logic of the program. They are generally preventable.</P>
<A NAME="idx422"><!></A>
<P><I>Runtime errors</I>, on the other hand, are generally not preventable, or at least not predictable. These are errors generated by circumstances outside the control of the program, such as peripheral hardware faults.</P>
<A NAME="1811"><H3>18.1.1 Include Files</H3></A>
<A NAME="idx423"><!></A>
<P>Programs that use the exception handling classes must include the following header file:</P>
<UL><PRE>
#include &lt;stdexcept&gt;
</PRE></UL>
<BR>
<HR>
<A HREF="18.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,61 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The Standard Exception Hierarchy</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="18-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>18.2 The Standard Exception Hierarchy</H2>
<A NAME="idx424"><!></A>
<P>The C++ Standard Library implements the two-category error model described in <A HREF="18-1.html">Section&nbsp;18.1</A> with a set of classes. These classes, which are defined in the <SAMP>stdexcept</SAMP> header file, can be used to catch exceptions thrown by the library and to throw exceptions from your own code.</P>
<P>The exception handling classes are related through inheritance. The inheritance hierarchy looks like this:</P>
<A NAME="idx425"><!></A>
<UL><PRE><B><I><A HREF="../stdlibref/exception.html">exception</A></I></B>
<B><I><A HREF="../stdlibref/logic-error.html">logic_error</A></I></B>
<B><I><A HREF="../stdlibref/domain-error.html">domain_error</A></I></B>
<B><I><A HREF="../stdlibref/invalid-argument.html">invalid_argument</A></I></B>
<B><I><A HREF="../stdlibref/length-error.html">length_error</A></I></B>
<B><I><A HREF="../stdlibref/out-of-range.html">out_of_range</A></I></B>
<B><I><A HREF="../stdlibref/runtime-error.html">runtime_error</A></I></B>
<B><I><A HREF="../stdlibref/range-error.html">range_error</A></I></B>
<B><I><A HREF="../stdlibref/overflow-error.html">overflow_error</A></I></B>
<B><I><A HREF="../stdlibref/underflow-error.html">underflow_error</A></I></B>
</PRE></UL>
<A NAME="idx426"><!></A>
<P>Classes <B><I><A HREF="../stdlibref/logic-error.html">logic_error</A></I></B> and <B><I><A HREF="../stdlibref/runtime-error.html">runtime_error</A></I></B> inherit from class <B><I><A HREF="../stdlibref/exception.html">exception</A></I></B>. All other exception handling classes inherit from either <B><I>logic_error</I></B> or <B><I>runtime_error</I></B>.</P>
<BR>
<HR>
<A HREF="18-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,87 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Using Exceptions</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="18-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>18.3 Using Exceptions</H2>
<A NAME="idx427"><!></A>
<P>All exceptions thrown explicitly by any element of the Apache C++ Standard Library are guaranteed to be part of the library's exception hierarchy. Please review the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A> entries for these classes to determine which functions throw which exceptions. You can then choose to catch particular exceptions, or catch any that might be thrown by specifying the base class exception. </P>
<P>For instance, if you are going to call the <SAMP>insert</SAMP> function on <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> with a position value that could at some point be invalid, you should use code like this:</P>
<UL><PRE>
string s;
int n;
...
try
{
s.insert(n,"Howdy");
}
catch (const std::exception&amp; e)
{
// deal with the exception
}
</PRE></UL>
<P>To throw your own exceptions, simply construct an exception of an appropriate type, assign it an appropriate message, and throw it. For example:</P>
<UL><PRE>
...
if (n &gt; max)
throw std::out_of_range("You're past the end, bud");
</PRE></UL>
<P>The class <B><I><A HREF="../stdlibref/exception.html">exception</A></I></B> serves as the base class for all other exception classes. As such it defines a standard interface. This interface includes the <SAMP>what()</SAMP> member function, which returns a null-terminated string that represents the message that was thrown with the exception. This function is likely to be most useful in a catch clause, as demonstrated in the example program in <A HREF="18-4.html">Section&nbsp;18.4</A>.</P>
<P>The class <B><I><A HREF="../stdlibref/exception.html">exception</A></I></B> does not contain a constructor that takes a message string, although it can be thrown without a message. Calling <SAMP>what()</SAMP> on an exception object returns a default message. All classes derived from <B><I>exception</I></B> <I>do</I> provide a constructor that allows you to specify a particular message.</P>
<P>To throw a base exception, you could use the following code:</P>
<UL><PRE>
throw std::exception;
</PRE></UL>
<P>This is generally not very useful, however, since whatever catches this exception has no idea what kind of error has occurred. Instead of a base exception, you will usually throw a derived class such as <B><I><A HREF="../stdlibref/logic-error.html">logic_error</A></I></B> or one of its derivations, such as <B><I><A HREF="../stdlibref/out-of-range.html">out_of_range</A></I></B> in the example above. Better still, you can extend the hierarchy by deriving your own classes. This allows you to provide error reporting specific to your particular problem. For instance:</P>
<UL><PRE>
class bad_packet_error : public std::runtime_error
{
public:
bad_packet_error(const std::string&amp; what);
};
if (bad_packet())
throw bad_packet_error("Packet size incorrect");
</PRE></UL>
<P>This section has demonstrated how the C++ Standard Library exception classes provide you with a basic error model. From this foundation, you can build the right error detection and reporting methods required for your particular application.</P>
<BR>
<HR>
<A HREF="18-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,103 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Example Program: Exceptions</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="18-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="VI.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>18.4 Example Program: Exceptions</H2>
<BLOCKQUOTE><HR><B>
NOTE -- This program is in the file <code>tutorial/stdexcept.cpp</code>.
</B><HR></BLOCKQUOTE>
<A NAME="idx428"><!></A>
<P>This following example program demonstrates the use of exceptions:</P>
<UL><PRE>
#include &lt;string&gt; // for string
#include &lt;stdexcept&gt; // for exception, runtime_error, out_of_range
#include &lt;iostream&gt; // for cout
int main ()
{
// First we'll incite and catch an exception from the C++ Standard
// library class std::string by attempting to replace a substring
// starting at a position beyond the end of the string object.
try {
std::string ().replace (100, 1, 1, 'c');
}
catch (std::out_of_range &amp;e) {
// Print out the exception string, which in this implementation
// includes the location and the name of the function that threw
// the exception along with the reason for the exception.
std::cout &lt;&lt; "Caught an out_of_range exception: "
&lt;&lt; e.what () &lt;&lt; '\n';
}
catch (std::exception &amp;e) {
std::cout &lt;&lt; "Caught an exception of an unexpected type: "
&lt;&lt; e.what () &lt;&lt; '\n';
}
catch (...) {
std::cout &lt;&lt; "Caught an unknown exception\n";
}
// Throw another exception.
try {
throw std::runtime_error ("a runtime error");
}
catch (std::runtime_error &amp;e) {
std::cout &lt;&lt; "Caught a runtime_error exception: "
&lt;&lt; e.what () &lt;&lt; '\n';
}
catch (std::exception &amp;e) {
std::cout &lt;&lt; "Caught an exception of an unexpected type: "
&lt;&lt; e.what () &lt;&lt; '\n';
}
catch (...) {
std::cout &lt;&lt; "Caught an unknown exception\n";
}
return 0;
}
</PRE></UL>
<P>The exact output of the program is specific to the compiler used to compile it and to the location of the library headers but may look something like this:</P><UL><PRE>
Caught an out_of_range exception: /usr/local/stdcxx/include/string.cc:422: std::string& std::string::replace(size_type, size_type, size_type, char_type): argument value 100 out of range [0, 0)
Caught a runtime_error exception: a runtime error
</UL></PRE>
<BR>
<HR>
<A HREF="18-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="VI.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,51 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Exception Handling</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="17-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 18: Exception Handling</H1>
<UL>
<UL><LI><A HREF="18-1.html">18.1 Overview</A></LI></UL>
<UL><UL><LI><A HREF="18-1.html#1811">18.1.1 Include Files</A></LI></UL></UL>
<UL><LI><A HREF="18-2.html">18.2 The Standard Exception Hierarchy</A></LI></UL>
<UL><LI><A HREF="18-3.html">18.3 Using Exceptions</A></LI></UL>
<UL><LI><A HREF="18-4.html">18.4 Example Program: Exceptions</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="17-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="18-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,52 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="19.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="19-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>19.1 Overview</H2>
<A NAME="idx429"><!></A>
<P>The <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B> class wraps any pointer obtained through <SAMP>new</SAMP> and provides automatic deletion of that pointer. The pointer wrapped by an <B><I>auto_ptr</I></B> object is deleted when the <B><I>auto_ptr</I></B> itself is destroyed.</P>
<A NAME="1911"><H3>19.1.1 Include File</H3></A>
<A NAME="idx430"><!></A>
<P>To access the <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B> class, include the memory header file: </P>
<UL><PRE>
#include &lt;memory&gt;
</PRE></UL>
<BR>
<HR>
<A HREF="19.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="19-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,67 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Declaration and Initialization of Autopointers</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="19-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="20.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>19.2 Declaration and Initialization of Autopointers</H2>
<A NAME="idx431"><!></A>
<P>You attach an <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B> object to a pointer either by using one of the constructors for <B><I>auto_ptr</I></B>, by assigning one <B><I>auto_ptr</I></B> object to another, or by using the reset member function. Only one <B><I>auto_ptr</I></B> owns a particular pointer at any one time, except for the null pointer, which all <B><I>auto_ptr</I></B>s own by default. Any use of the <B><I>auto_ptr</I></B> copy constructor or assignment operator transfers ownership from one <B><I>auto_ptr</I></B> object to another. For instance, suppose we create an <B><I>auto_ptr</I></B> <SAMP>a</SAMP> like this:</P>
<UL><PRE>
std::auto_ptr&lt;std::string&gt; a(new std::string);
</PRE></UL>
<P>The <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B> object <SAMP>a</SAMP> now owns the newly created pointer. When <SAMP>a</SAMP> is destroyed, such as when it goes out of scope, the pointer is deleted. But if we initialize <SAMP>b</SAMP> with the value of <SAMP>a</SAMP>:</P>
<UL><PRE>
std::auto_ptr&lt;std::string&gt; b = a;
</PRE></UL>
<P><SAMP>b</SAMP> now owns the pointer. Use of the copy constructor or the assignment operator causes <SAMP>a</SAMP> to release ownership of the pointer. Now if <SAMP>a</SAMP> goes out of scope the pointer is not affected. However, the pointer <I>is</I> deleted when <SAMP>b</SAMP> goes out of scope.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The standard container templates cannot be specialized on <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B> objects. Copying or assigning from an <B><I>auto_ptr</I></B> object transfers ownership of the contained pointer, which changes the source object. Therefore, <B><I>auto_ptr</I></B> objects do not meet the Assignable and CopyConstructible requirements of standard containers. See <A HREF="4.html">Chapter&nbsp;4</A> for container requirements.
</B><HR></BLOCKQUOTE>
<P>The use of <SAMP>new</SAMP> within the constructor for <SAMP>a</SAMP> may seem a little odd. Normally we avoid constructs like this since it puts the responsibility for deletion on a different entity than the one responsible for allocation. In this case, however, the sole responsibility of the <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B> is to manage the deletion. This syntax is actually preferable since it prevents us from accidentally deleting the pointer ourselves. or initializing another <B><I>auto_ptr</I></B> object with it.</P>
<P>Use <SAMP>operator*()</SAMP>, <SAMP>operator-&gt;()</SAMP> or the member function <SAMP>get()</SAMP> to access the pointer held by an <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B>. For instance, we can use any of the three following statements to assign <SAMP>"What's up Doc"</SAMP> to the string now pointed to by the <B><I>auto_ptr</I></B> <SAMP>b</SAMP>:</P>
<UL><PRE>
*b = "What's up Doc";
*(b.get()) = "What's up Doc";
b-&gt;assign("What's up Doc");
</PRE></UL>
<P>Class <B><I><A HREF="../stdlibref/auto-ptr.html">auto_ptr</A></I></B> also provides a release member function that releases ownership of a pointer. Any <B><I>auto_ptr</I></B> that does not own a specific pointer is assumed to contain the null pointer, so calling release on an <B><I>auto_ptr</I></B> will set the contained pointer to zero. In the example above, when <SAMP>a</SAMP> is copied to <SAMP>b</SAMP>, the pointer held by <SAMP>a</SAMP> is released and set to the null pointer.</P>
<BR>
<HR>
<A HREF="19-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="20.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,49 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>auto_ptr</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="VI.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="19-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 19: auto_ptr</H1>
<UL>
<UL><LI><A HREF="19-1.html">19.1 Overview</A></LI></UL>
<UL><UL><LI><A HREF="19-1.html#1911">19.1.1 Include File</A></LI></UL></UL>
<UL><LI><A HREF="19-2.html">19.2 Declaration and Initialization of Autopointers</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="VI.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="19-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,58 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Introduction to Iterators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>2.1 Introduction to Iterators</H2>
<A NAME="idx11"><!></A>
<P>The concept of iterators is fundamental to using the container classes and the associated algorithms provided by the C++ Standard Library. An <I>iterator</I> is a pointer-like object used to cycle through all the elements stored in a container. Because different algorithms need to traverse containers in a variety of fashions, there are different forms of iterators. Each container class in the C++ Standard Library can generate an iterator with functionality appropriate to the storage technique used in implementing the container. It is the category of iterators required as arguments that chiefly distinguishes which algorithms in the C++ Standard Library can be used with which container classes. </P>
<A NAME="idx12"><!></A>
<P>Just as pointers can be used in a variety of ways in traditional programming, iterators can be used for a number of different purposes. An iterator can be used to denote a specific value, just as a pointer can be used to reference a specific memory location. A <I>pair</I> of iterators can be used to define a <I>range</I> or sequence of values held in a container, just as two pointers can be used to describe a contiguous region of memory. With iterators, however, the values being described may be only logically rather than physically in sequence because they are derived from the same container, and the second follows the first in the order in which the elements are maintained by the container.</P>
<A NAME="idx13"><!></A>
<P>Conventional pointers can sometimes be <I>null</I>, meaning they point at nothing. Iterators, as well, can fail to denote any specific value. Just as it is a logical error to dereference a null pointer, it is an error to dereference an iterator that is not denoting a value. </P>
<P>When two pointers that describe a region in memory are used in a C++ program, it is conventional that the ending pointer <I>not</I> be considered part of the region. For example, an array named <SAMP>x</SAMP> of length <SAMP>10</SAMP> is sometimes described as extending from <SAMP>x</SAMP> to <SAMP>x+10</SAMP>, even though the element at <SAMP>x+10</SAMP> is not part of the array. Instead, the pointer value <SAMP>x+10</SAMP> is the<I> past-the-end</I> value <I>after</I> the end of the range being described. Iterators are used similarly to describe a range. The second value is not considered part of the range being denoted. Instead, the second value is a <I>past-the-end</I> element describing the next value in sequence after the final value of the range. Sometimes, as with pointers to memory, this will be an actual value in the container. Other times it may be a special value, specifically constructed for the purpose. In either case, it is not proper to dereference an iterator that is being used to specify the end of a range. </P>
<A NAME="idx14"><!></A>
<P>Just as with conventional pointers, the fundamental operation used to modify an iterator is the increment operator, <SAMP>operator++()</SAMP>. When the increment operator is applied to an iterator that denotes the final value in a sequence, the iterator is changed to the past-the-end value. An iterator <SAMP>j</SAMP> is said to be <I>reachable</I> from an iterator <SAMP>i</SAMP> if, after a finite sequence of applications of the expression <SAMP>++i</SAMP>, the iterator <SAMP>i</SAMP> becomes equal to <SAMP>j</SAMP>.</P>
<A NAME="idx15"><!></A>
<P>Ranges can be used to describe the entire contents of a container by constructing an iterator to the initial element and a special <I>ending</I> iterator. Ranges can also be used to describe sub-sequences within a single container by employing two iterators to specific values. </P>
<BLOCKQUOTE><HR><B>
NOTE -- Whenever two iterators are used to describe a range, it is assumed that the second iterator is reachable from the first, but this is not verified. Errors can occur if this expectation is not satisfied.
</B><HR></BLOCKQUOTE>
<P>In the remainder of this chapter, we describe the different forms of iterators used by the C++ Standard Library, as well as various other iterator-related functions.</P>
<BR>
<HR>
<A HREF="2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,270 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Varieties of Iterators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="2-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>2.2 Varieties of Iterators</H2>
<A NAME="idx16"><!></A>
<P>As shown in <A HREF="2-2.html#Table&nbsp;3">Table&nbsp;3</A>, there are five basic forms of iterators used in the C++ Standard Library:</P>
<H4><A NAME="Table&nbsp;3">Table&nbsp;3: Iterator forms in the C++ Standard Library&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B><B>Iterator form</B></B>
</td><td valign=top><B><B>Description</B></B>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">input iterator </P>
</td><td valign=top><P CLASS="TABLE">Read only, forward moving </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">output iterator </P>
</td><td valign=top><P CLASS="TABLE">Write only, forward moving </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">forward iterator</P>
</td><td valign=top><P CLASS="TABLE">Both read and write, forward moving </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">bidirectional iterator </P>
</td><td valign=top><P CLASS="TABLE">Read and write, forward and backward moving </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">random access iterator</P>
</td><td valign=top><P CLASS="TABLE">Read and write, random access </P>
</td></tr>
</TABLE>
<A NAME="idx17"><!></A>
<P>Iterator categories are hierarchical. <I>Forward iterators</I> can be used wherever input or output iterators are required, <I>bidirectional iterators</I> can be used in place of forward iterators, and <I>random access iterators</I> can be used in situations requiring bidirectionality. </P>
<A NAME="idx18"><!></A>
<P>A second characteristic of iterators is whether or not they can be used to modify the values held by their associated container. A <I>constant iterator</I> is one that can be used for access only, and cannot be used for modification. <I>Output iterators</I> are never constant, and <I>input iterators</I> always are. Other iterators may or may not be constant, depending upon how they are created. There are both constant and non-constant bidirectional iterators, both constant and non-constant random access iterators, and so on.</P>
<P><A HREF="2-2.html#Table&nbsp;4">Table&nbsp;4</A> summarizes specific ways that various categories of iterators are generated by the containers in the C++ Standard Library.</P>
<H4><A NAME="Table&nbsp;4">Table&nbsp;4: Iterators generated in the C++ Standard Library&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Iterator form</B>
</td><td valign=top><B> Produced by</B>
</td></tr>
<A NAME="idx19"><!></A>
<tr><td valign=top><P CLASS="TABLE">input iterator</P>
</td><td valign=top><P CLASS="TABLE"><SAMP>istream_iterator</SAMP></P>
</td></tr>
<A NAME="idx20"><!></A>
<tr><td valign=top><P CLASS="TABLE">output iterator </P>
</td><td valign=top><P CLASS="TABLE"><SAMP>ostream_iterator</SAMP></P>
<P CLASS="TABLE"><SAMP>inserter()</SAMP></P>
<P CLASS="TABLE"><SAMP>front_inserter()</SAMP></P>
<P CLASS="TABLE"><SAMP>back_inserter()</SAMP></P>
</td></tr>
<A NAME="idx21"><!></A>
<tr><td valign=top><P CLASS="TABLE">bidirectional iterator </P>
</td><td valign=top><P CLASS="TABLE"><B><I><A HREF="../stdlibref/list.html">list</A></I></B> </P>
<P CLASS="TABLE"><B><I><A HREF="../stdlibref/set.html">set</A></I></B> and <B><I><A HREF="../stdlibref/multiset.html">multiset</A></I></B> </P>
<P CLASS="TABLE"><B><I><A HREF="../stdlibref/map.html">map</A></I></B> and <B><I><A HREF="../stdlibref/multimap.html">multimap</A></I></B></P>
</td></tr>
<A NAME="idx22"><!></A>
<tr><td valign=top><P CLASS="TABLE">random access iterator </P>
</td><td valign=top><P CLASS="TABLE">ordinary pointers </P>
<P CLASS="TABLE"><B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> </P>
<P CLASS="TABLE"><B><I><A HREF="../stdlibref/deque.html">deque</A></I></B></P>
</td></tr>
</TABLE>
<P>In the following sections we describe the capabilities and construction of each form of iterator.</P>
<A NAME="221"><H3>2.2.1 Input Iterators</H3></A>
<A NAME="idx23"><!></A>
<P>Input iterators are the simplest form of iterator. To understand their capabilities, consider an example algorithm: </P>
<UL><PRE>
template &lt;class InputIterator, class T&gt;
InputIterator
find (InputIterator first, InputIterator last,
const T&amp; value)
{
while (first != last &amp;&amp; *first != value)
++first;
return first;
}
</PRE></UL>
<P>This algorithm, which is similar to the <SAMP>std::find()</SAMP> generic algorithm (<A HREF="13-3.html#1331">Section&nbsp;13.3.1</A>), performs a simple linear search, looking for a specific value being held within a container. The contents of the container are described using two iterators, <SAMP>first</SAMP> and <SAMP>last</SAMP>. While <SAMP>first</SAMP> is not equal to <SAMP>last</SAMP>, the element denoted by <SAMP>first</SAMP> is compared to the test value. If this element is equal to the test value, the iterator, which now denotes the located element, is returned. If it is not equal, the <SAMP>first</SAMP> iterator is incremented and the loop cycles once more. If the entire region of memory is examined without finding the desired value, then the algorithm returns the end-of-range iterator.</P>
<P>This algorithm illustrates three features of an <I>input iterator</I>:</P>
<UL>
<LI><P CLASS="LIST">An input iterator can be compared for equality to another iterator. They are equal when they point to the same position, and not equal otherwise.</P></LI>
<LI><P CLASS="LIST">An input iterator can be dereferenced, using <SAMP>operator*()</SAMP> to obtain the value being denoted by the iterator.</P></LI>
<LI><P CLASS="LIST">An input iterator can be incremented, so that it refers to the next element in sequence, using <SAMP>operator++()</SAMP>.</P></LI>
</UL>
<P>Notice that these features can all be provided with new meanings in a C++ program, since the behavior of the given functions can all be modified by overloading the appropriate operators. Because of this overloading, iterators are possible. </P>
<A NAME="221-1"><H4>2.2.1.1 Kinds of Input Iterators</H4></A>
<A NAME="idx24"><!></A>
<P>There are three main kinds of input iterators: ordinary pointers, container iterators, and input streams iterators.</P>
<A NAME="idx25"><!></A>
<P><B>Ordinary pointers</B>. Ordinary pointers can be used as input iterators. In fact, since we can subscript and add to ordinary pointers, they are random access values, and thus can be used either as input or output iterators. The end-of-range pointer describes the end of a contiguous region of memory, and the dereference and increment operators have their conventional meanings. For example, the following code searches for the value 7 in an array of integers:</P>
<UL><PRE>
int data[100];
...
int* where = std::find(data, data+100, 7);
</PRE></UL>
<P>Note that constant pointers, which do not permit the underlying array to be modified, can be created by simply placing the keyword <SAMP>const</SAMP> in a declaration:</P>
<UL><PRE>
const int* first = data;
const int* last = data + 100;
// can't modify location returned by the following
const int* where = std::find(first, last, 7);
</PRE></UL>
<P>Because ordinary pointers have the same functionality as random access iterators, most of the generic algorithms in the C++ Standard Library can be used with conventional C++ arrays, as well as with the containers provided by the C++ Standard Library.</P>
<A NAME="idx26"><!></A>
<P><B>Container iterators</B>. All of the iterators constructed for the various containers provided by the C++ Standard Library are at <I>least</I> as general as input iterators. The iterator for the first element in a collection is always constructed by the member function<SAMP> begin()</SAMP>, while the iterator that denotes the past-the-end location is generated by the member function <SAMP>end()</SAMP>. For example, the following iterator searches for the value 7 in a list of integers:</P>
<UL><PRE>
std::list&lt;int&gt;::iterator where =
std::find(aList.begin(), aList.end(), 7);
</PRE></UL>
<P>Each container that supports iterators provides a type with the name <SAMP>iterator </SAMP>within the class declaration. Using this type, iterators can uniformly be declared in the fashion shown. If the container being accessed is constant, or if the description <SAMP>const_iterator</SAMP> is used, then the iterator is a constant iterator.</P>
<A NAME="idx27"><!></A>
<P><B>Input stream iterators</B>. The C++ Standard Library provides a mechanism to operate on an input stream using an input iterator. This ability is provided by the class <B><I><A HREF="../stdlibref/istream-iterator.html">istream_iterator</A></I></B>, described in more detail in <A HREF="2-3.html#231">Section&nbsp;2.3.1</A>.</P>
<A NAME="222"><H3>2.2.2 Output Iterators</H3></A>
<A NAME="idx28"><!></A>
<P>An <I>output iterator</I> has the opposite function of an input iterator. Output iterators can be used to assign values in a sequence, but cannot be used to access values. For example, we can use an output iterator in a generic algorithm that copies values from one sequence into another:</P>
<UL><PRE>
template &lt;class InputIterator, class OutputIterator&gt;
OutputIterator copy
(InputIterator first, InputIterator last, OutputIterator result)
{
while (first != last)
*result++ = *first++;
return result;
}
</PRE></UL>
<P>A number of the generic algorithms manipulate two parallel sequences. Frequently the second sequence is described using only a beginning iterator, rather than an iterator pair. It is assumed, but not checked, that the second sequence has at least as many elements as the first.</P>
<P>In the algorithm shown here, two ranges are being manipulated: the range of source values specified by a pair of input iterators, and the destination range. The latter, however, is specified by only a single argument. It is assumed that the destination is large enough to include all values, and errors will ensue if this is not the case.</P>
<P>As illustrated by this algorithm, an output iterator can modify the element to which it points by being used as the target for an assignment. Output iterators can use the dereference operator only in this fashion; they cannot be used to return or to access the elements they denote. </P>
<P>As we noted earlier, ordinary pointers, like all iterators constructed by containers in the C++ Standard Library, can be used as output iterators. (Ordinary pointers are random access iterators, which are a superset of output iterators.) For example, in this code fragment elements from an ordinary C-style array are copied into a C++ Standard Library vector:</P>
<UL><PRE>
int data[100];
std::vector&lt;int&gt; newdata(100);
...
std::copy(data, data+100, newdata.begin());
</PRE></UL>
<P>Just as the <SAMP>istream_iterator</SAMP> provides a way to operate on an input stream using the input iterator mechanism, the C++ Standard Library provides a datatype, <SAMP>ostream_iterator</SAMP>, that permits values to be written to an output stream in an iterator-like fashion (<A HREF="2-3.html#232">Section&nbsp;2.3.2</A>).</P>
<P>Yet another form of output iterator is an <I>insert iterator </I>(<A HREF="2-4.html">Section&nbsp;2.4</A>). An insert iterator changes the output iterator operations of dereferencing/assignment and increment into insertions into a container. This permits operations such as <SAMP>copy()</SAMP> to be used with variable length containers, such as <B><I><A HREF="../stdlibref/list.html">list</A></I></B>s and <B><I><A HREF="../stdlibref/set.html">set</A></I></B>s.</P>
<A NAME="223"><H3>2.2.3 Forward Iterators</H3></A>
<A NAME="idx29"><!></A>
<P>A <I>forward iterator </I>combines the features of an input iterator and an output iterator. It permits values to be both accessed and modified. One function that uses forward iterators is the <SAMP>replace()</SAMP> generic algorithm, which replaces occurrences of specific values with other values. This algorithm could be written as follows:</P>
<UL><PRE>
template &lt;class ForwardIterator, class T&gt;
void
replace(ForwardIterator first, ForwardIterator last,
const T&amp; old_value, const T&amp; new_value)
{
while (first != last)
{
if (*first == old_value)
*first = new_value;
++first;
}
}
</PRE></UL>
<P>Ordinary pointers, like all iterators produced by containers in the C++ Standard Library, can be used as forward iterators. For example, in the following code instances of the value 7 are replaced with the value 11 in a vector of integers:</P>
<UL><PRE>
std::replace(aVec.begin(), aVec.end(), 7, 11);
</PRE></UL>
<A NAME="224"><H3>2.2.4 Bidirectional Iterators</H3></A>
<A NAME="idx30"><!></A>
<P><I>Bidirectional iterators</I> are similar to forward iterators, except that bidirectional iterators support the decrement operator, <SAMP>operator--()</SAMP>, permitting movement in either a forward or a backward direction through the elements of a container. For example, we can use bidirectional iterators in a function that reverses the values of a container, placing the results into a new container:</P>
<UL><PRE>
template &lt;class BidirectionalIterator, class OutputIterator&gt;
OutputIterator
reverse_copy(BidirectionalIterator first,
BidirectionalIterator last,
OutputIterator result)
{
while (first != last)
*result++ = *--last;
return result;
}
</PRE></UL>
<P>As always, the value initially denoted by the <SAMP>last</SAMP> argument is not considered part of the collection.</P>
<A NAME="idx31"><!></A>
<P>The <SAMP>reverse_copy()</SAMP> function could be used, for example, to reverse the values of a linked list, and place the result into a vector:</P>
<UL><PRE>
std::list&lt;int&gt; aList;
....
std::vector&lt;int&gt; aVec (aList.size());
std::reverse_copy(aList.begin(), aList.end(), aVec.begin() );
</PRE></UL>
<A NAME="225"><H3>2.2.5 Random Access Iterators</H3></A>
<A NAME="idx32"><!></A>
<P>Some algorithms require more functionality than simply accessing values in either a forward or backward direction. Random access iterators permit values to be accessed by subscript, subtracted one from another (to yield the number of elements between their respective values), or modified by arithmetic operations, all in a manner similar to conventional pointers.</P>
<P>With conventional pointers, arithmetic operations can be related to the underlying memory; that is, <SAMP>x+10</SAMP> is the memory ten elements after the beginning of <SAMP>x</SAMP>. With iterators the logical meaning is preserved (<SAMP>x+10</SAMP> is the tenth element after <SAMP>x</SAMP>), however different the physical addresses being described.</P>
<P>Algorithms that use random access iterators include generic operations like sorting and binary search. For example, the following algorithm randomly shuffles the elements of a container. This is similar to, although simpler than, the function <SAMP>std::random_shuffle()</SAMP> provided by the C++ Standard Library.</P>
<UL><PRE>
template &lt;class RandomAccessIterator&gt;
void
mixup(RandomAccessIterator first, RandomAccessIterator last)
{
while (first &lt; last)
{
std::iter_swap(first, first + randomInteger(last - first));
++first;
}
}
</PRE></UL>
<BLOCKQUOTE><HR><B>
NOTE -- The function randomInteger described here appears in a number of the example programs presented in later sections.
</B><HR></BLOCKQUOTE>
<A NAME="idx33"><!></A>
<P>The program will cycle as long as <SAMP>first</SAMP> denotes a position that occurs earlier in the sequence than the one denoted by <SAMP>last</SAMP>. Only random access iterators can be compared using relational operators; all other iterators can be compared only for equality or inequality. On each cycle through the loop, the expression <br><SAMP>last - first</SAMP> yields the number of elements between the two limits. The function <SAMP>randomInteger()</SAMP> is assumed to generate a random number between 0 and the argument. Using the standard random number generator, this function could be written as follows:</P>
<UL><PRE>
unsigned int randomInteger(unsigned int n)
// return random integer greater than
// or equal to 0 and less than n
{
return std::rand() % n;
}
</PRE></UL>
<P>This random value is added to the iterator <SAMP>first</SAMP>, resulting in an iterator to a randomly selected value in the container. This value is then swapped with the element denoted by the iterator <SAMP>first</SAMP>.</P>
<A NAME="226"><H3>2.2.6 Reverse Iterators</H3></A>
<A NAME="idx34"><!></A>
<P>An iterator naturally imposes an order on an underlying container of values. For a <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> or a <B><I><A HREF="../stdlibref/map.html">map</A></I></B>, the order is imposed by increasing index values; for a <B><I><A HREF="../stdlibref/set.html">set</A></I></B>, by the increasing order of the elements held in the container. For a <B><I><A HREF="../stdlibref/list.html">list</A></I></B>, the order is explicitly derived from the way values are inserted.</P>
<P>A <I>reverse iterator</I> yields values in exactly the reverse order of values given by the standard iterators. For a vector or a list, a reverse iterator generates the last element first, and the first element last. For a set it generates the largest element first, and the smallest element last. Strictly speaking, reverse iterators do not constitute a new category of iterator, but an adaptation of another iterator type. Consequently, we have reverse bidirectional iterators and reverse random access iterators. Any bidirectional or random access iterator can be adapted by the <SAMP>reverse_iterator</SAMP> template.</P>
<P>The <B><I><A HREF="../stdlibref/list.html">list</A></I></B>, <B><I><A HREF="../stdlibref/set.html">set</A></I></B>, and <B><I><A HREF="../stdlibref/map.html">map</A></I></B> datatypes provide a pair of member functions that produce reverse bidirectional iterators. The functions <SAMP>rbegin()</SAMP> and <SAMP>rend()</SAMP> generate iterators that cycle through the underlying container in reverse order. Increments to such iterators move backward, and decrements move forward through the sequence.</P>
<P>Similarly, the <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B> and <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B> datatypes provide functions, also named <SAMP>rbegin()</SAMP> and <SAMP>rend()</SAMP>, that produce reverse random access iterators. Subscript and addition operators, as well as increments to such iterators, move backward within the sequence.</P>
<BR>
<HR>
<A HREF="2-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,74 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Stream Iterators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="2-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>2.3 Stream Iterators</H2>
<A NAME="idx35"><!></A>
<P>Stream iterators are used to access an existing input or output stream using iterator operations. An input stream iterator permits an input stream to be read using iterator operations. Similarly, an output stream iterator writes to an output stream when iterator operations are executed.</P>
<A NAME="231"><H3>2.3.1 Input Stream Iterators</H3></A>
<A NAME="idx36"><!></A>
<P>As we noted in the discussion of input iterators, the C++ Standard Library provides a mechanism for turning an input stream into an input iterator through the <SAMP>template &lt;class T, class charT, class Traits, class Distance&gt; std::istream_iterator</SAMP> . When declared, the four template arguments are the element type, the stream character type, the character traits type, and a type that measures the distance between elements. The latter two default to <SAMP>std::char_traits&lt;charT</SAMP> &gt; and <SAMP>std::ptrdiff_t.</SAMP> The default is almost always the appropriate behavior. The single argument provided to the constructor for an <SAMP>istream_iterator</SAMP> is the stream to be accessed. Each time that <SAMP>operator++()</SAMP> is invoked on an input stream iterator, a new value from the stream is read using <SAMP>operator&gt;&gt;()</SAMP> and stored. This value is then available through the use of the dereference operator <SAMP>operator*()</SAMP>. The value constructed by <SAMP>istream_iterator</SAMP> when no arguments are provided to the constructor can be used as an ending iterator value. For example, the following code finds the first value 7 in a file of integer values:</P>
<UL><PRE>
std::istream_iterator&lt;int, char&gt; intstream(std::cin), eof;
std::istream_iterator&lt;int, char&gt;::iterator where =
std::find(intstream, eof, 7);
</PRE></UL>
<P>The element denoted by an iterator for an input stream is valid only until the next element in the stream is requested. Also, since an input stream iterator is an input iterator, elements can only be accessed, not modified by assignment. Finally, elements can be accessed only once, and only in a forward moving direction.</P>
<A NAME="232"><H3>2.3.2 Output Stream Iterators</H3></A>
<A NAME="idx37"><!></A>
<P>The output stream iterator mechanism is analogous to the input stream iterator. Each time a value is assigned to the iterator, it is written on the associated output stream using <SAMP>operator&gt;&gt;()</SAMP>. To create an output stream iterator, you must specify the associated output stream as an argument with the constructor. Values written to the output stream must recognize the stream <SAMP>&gt;&gt;</SAMP> operation. An optional second argument to the constructor is a string used as a separator between each pair of values. For example, the following code copies all the values from a vector into the standard output, and separates each value by a space:</P>
<UL><PRE>
std::copy(newdata.begin(), newdata.end(),
std::ostream_iterator&lt;int,char&gt; (std::cout, " "));
</PRE></UL>
<P>Simple file transformation algorithms can be created by combining input and output stream iterators and the various algorithms provided by the C++ Standard Library. The following short program reads a file of integers from the standard input, removes all occurrences of the value 7, and copies the remainder to the standard output, separating each value by a new line:</P>
<UL><PRE>
int main()
{
std::istream_iterator&lt;int, char&gt; input(std::cin), eof;
std::ostream_iterator&lt;int, char&gt; output(std::cout, "\n");
std::remove_copy(input, eof, output, 7);
}
</PRE></UL>
<BR>
<HR>
<A HREF="2-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,100 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Insert Iterators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="2-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-5.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>2.4 Insert Iterators</H2>
<A NAME="idx38"><!></A>
<P>Assignment to the dereferenced value of an output iterator is normally used to <I>overwrite </I>the contents of an existing location. For example, the following invocation of the function <SAMP>std::copy()</SAMP> transfers values from one vector to another, although the space for the second vector was already set aside and even initialized by the declaration statement:</P>
<UL><PRE>
std::vector&lt;int&gt; a(10);
std::vector&lt;int&gt; b(10);
// ...
std::copy(a.begin(), a.end(), b.begin());
</PRE></UL>
<P>Even structures such as lists can be overwritten in this fashion. In the following code, the list named <SAMP>c</SAMP> is assumed to have at least ten elements. The initial ten locations in the list will be replaced by the contents of the vector <SAMP>a</SAMP>.</P>
<UL><PRE>
std::list&lt;int&gt; c;
// ...
std::copy(a.begin(), a.end(), c.begin());
</PRE></UL>
<P>With structures such as lists and sets, which are dynamically enlarged as new elements are added, it is frequently more appropriate to<I> insert</I> new values into the structure, rather than to <I>overwrite</I> existing locations. A type of adaptor called an <I>insert iterator</I> allows us to use algorithms such as <SAMP>std::copy()</SAMP> to insert into the associated container, rather than overwrite elements in the container. The output operations of the iterator are changed into insertions into the associated container. For example, the following code inserts the values of the vector <SAMP>a</SAMP> into an initially empty list:</P>
<UL><PRE>
std::list&lt;int&gt; d;
std::copy(a.begin(), a.end(), std::front_inserter(d));
</PRE></UL>
<A NAME="idx39"><!></A>
<P>There are three forms of insert iterators, all of which can be used to change a <I>copy</I> operation into an <I>insert</I> operation. The iterator generated using <SAMP>std::front_inserter()</SAMP>, shown above, inserts values into the front of the container. The iterator generated by <SAMP>std::back_inserter()</SAMP> places elements into the back of the container. Both forms can be used with <B><I><A HREF="../stdlibref/list.html">list</A></I></B>s and <B><I><A HREF="../stdlibref/deque.html">deque</A></I></B>s, but not with <B><I><A HREF="../stdlibref/set.html">set</A></I></B>s or <B><I><A HREF="../stdlibref/map.html">map</A></I></B>s. The iterator generated by <SAMP>std::back_inserter()</SAMP>, but not by <SAMP>std::front_inserter()</SAMP>, can be used with <B><I><A HREF="../stdlibref/vector.html">vector</A></I></B>.</P>
<A NAME="idx40"><!></A>
<P>The third and most general form of insert iterator is that generated by <SAMP>std::inserter()</SAMP>, which takes two arguments: a container and an iterator within the container. This form copies elements into the specified location in the container. (For a <B><I><A HREF="../stdlibref/list.html">list</A></I></B>, this means elements are copied immediately before the specified location). This form can be used with all the structures for which the previous two forms work, as well as with sets and maps.</P>
<P>The following simple program illustrates the use of all three forms of insert iterators. First, the values 3, 2, and 1 are inserted into the front of an initially empty list. Note that as each value is inserted, it becomes the new front, so that the resultant list is ordered 1, 2, 3. Next, the values 7, 8, and 9 are inserted into the end of the list. Finally, the <SAMP>find()</SAMP> operation is used to locate an iterator that denotes the 7 value, and the numbers 4, 5, and 6 are inserted immediately prior. The result is the list of numbers from 1 to 9 in order.</P>
<UL><PRE>
int main() {
int threeToOne[] = {3, 2, 1};
int fourToSix[] = {4, 5, 6};
int sevenToNine[] = {7, 8, 9};
std::list&lt;int&gt; aList;
// first insert into the front
// note that each value becomes new front
std::copy(threeToOne, threeToOne+3, std::front_inserter(aList));
// then insert into the back
std::copy(sevenToNine, sevenToNine+3,
std::back_inserter(aList));
// find the seven, and insert into middle
std::list&lt;int&gt;::iterator seven =
std::find(aList.begin(), aList.end(), 7);
std::copy(fourToSix, fourToSix+3, std::inserter(aList, seven));
// copy result to output
std::copy (aList.begin(), aList.end(),
std::ostream_iterator&lt;int,char&gt;(std::cout, " "));
std::cout &lt;&lt; std::endl;
}
</PRE></UL>
<P>Note that there is an important and subtle difference between the iterator created by <SAMP>std::inserter()</SAMP> and the iterator created by <SAMP>std::front_inserter().</SAMP> The call on <SAMP>std::inserter()</SAMP> copies values in sequence, adding each one to the front of a list, whereas <SAMP>std::front_inserter()</SAMP> copies values making each value the new front. The result is that <SAMP>std::front_inserter()</SAMP> reverses the order of the original sequence, while <SAMP>std::inserter()</SAMP> retains the original order.</P>
<BR>
<HR>
<A HREF="2-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-5.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,66 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Iterator Operations</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="2-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>2.5 Iterator Operations</H2>
<A NAME="idx41"><!></A>
<P>The C++ Standard Library provides two functions that can be used to manipulate iterators. The function <SAMP>std::advance()</SAMP> takes an iterator and a numeric value as argument, and modifies the iterator by moving the given amount.</P>
<UL><PRE>
namespace std {
template &lt;class InputIterator, class Distance&gt;
void advance(InputIterator&amp; iter, Distance&amp; n);
}
</PRE></UL>
<P>For random access iterators this is the same as <SAMP>iter + n;</SAMP> however, the function is useful because it is designed to operate with all forms of iterators. For forward iterators the numeric distance must be positive, whereas for bidirectional or random access iterators the value can be either positive or negative. The operation is efficient (constant time) only for random access iterators. In all other cases, it is implemented as a loop that invokes either <SAMP>operator++()</SAMP> or <SAMP>operator--()</SAMP> on the iterator, and therefore takes time proportional to the distance traveled. The <SAMP>std::advance()</SAMP> function does not check to ensure the validity of the operations on the underlying iterator.</P>
<A NAME="idx42"><!></A>
<P>The second function, <SAMP>std::distance()</SAMP>, returns the number of iterator operations necessary to move from one element in a sequence to another. The description of this function is as follows:</P>
<UL><PRE>
namespace std {
template &lt;class InputIterator&gt;
Distance distance(InputIterator first, InputIterator last);
}
</PRE></UL>
<P>The result returned is the number of times that <SAMP>first</SAMP> must be incremented or decremented in order for <SAMP>(first == last)</SAMP> to equal<SAMP> true</SAMP>. The function requires that <SAMP>last</SAMP> be reachable from <SAMP>first</SAMP>.</P>
<BLOCKQUOTE><HR><B>
NOTE -- The above definition of distance assumes that your compiler supports partial specialization. If it does not, then you must use the following alternate definition:<br>template &lt;class InputIterator, class Distance&gt;<br>void distance(InputIterator first, InputIterator last, Distance&amp; n);
</B><HR></BLOCKQUOTE>
<BR>
<HR>
<A HREF="2-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

60
extern/stdcxx/4.2.1/doc/stdlibug/2.html vendored Normal file
View File

@@ -0,0 +1,60 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Iterators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="II.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 2: Iterators</H1>
<UL>
<UL><LI><A HREF="2-1.html">2.1 Introduction to Iterators</A></LI></UL>
<UL><LI><A HREF="2-2.html">2.2 Varieties of Iterators</A></LI></UL>
<UL><UL><LI><A HREF="2-2.html#221">2.2.1 Input Iterators</A></LI></UL></UL>
<UL><UL><UL><LI><A HREF="2-2.html#221-1">2.2.1.1 Kinds of Input Iterators</A></LI></UL></UL></UL>
<UL><UL><LI><A HREF="2-2.html#222">2.2.2 Output Iterators</A></LI></UL></UL>
<UL><UL><LI><A HREF="2-2.html#223">2.2.3 Forward Iterators</A></LI></UL></UL>
<UL><UL><LI><A HREF="2-2.html#224">2.2.4 Bidirectional Iterators</A></LI></UL></UL>
<UL><UL><LI><A HREF="2-2.html#225">2.2.5 Random Access Iterators</A></LI></UL></UL>
<UL><UL><LI><A HREF="2-2.html#226">2.2.6 Reverse Iterators</A></LI></UL></UL>
<UL><LI><A HREF="2-3.html">2.3 Stream Iterators</A></LI></UL>
<UL><UL><LI><A HREF="2-3.html#231">2.3.1 Input Stream Iterators</A></LI></UL></UL>
<UL><UL><LI><A HREF="2-3.html#232">2.3.2 Output Stream Iterators</A></LI></UL></UL>
<UL><LI><A HREF="2-4.html">2.4 Insert Iterators</A></LI></UL>
<UL><LI><A HREF="2-5.html">2.5 Iterator Operations</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="II.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="2-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,52 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="20.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="20-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>20.1 Overview</H2>
<A NAME="idx432"><!></A>
<P>The class <B><I><A HREF="../stdlibref/complex.html">complex</A></I></B> is a template class used to create objects for representing and manipulating complex numbers. The operations defined on complex numbers allow them to be freely intermixed with the other numeric types available in the C++ language, thereby permitting numeric software to be easily and naturally expressed.</P>
<A NAME="2011"><H3>20.1.1 Include Files</H3></A>
<A NAME="idx433"><!></A>
<P>Programs that use complex numbers must include the <SAMP>complex</SAMP> header file:</P>
<UL><PRE>
#include &lt;complex&gt;
</PRE></UL>
<BR>
<HR>
<A HREF="20.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="20-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,127 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Creating and Using Complex Numbers</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="20-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="20-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>20.2 Creating and Using Complex Numbers</H2>
<P>In the following sections we describe the operations used to create and manipulate complex numbers.</P>
<A NAME="2021"><H3>20.2.1 Declaring Complex Numbers</H3></A>
<A NAME="idx434"><!></A>
<P>The template argument is used to define the types associated with the real and imaginary fields. This argument must be one of the floating point number datatypes available in the C++ language, either <SAMP>float</SAMP>, <SAMP>double</SAMP>, or <SAMP>long</SAMP> <SAMP>double</SAMP>.</P>
<P>There are several constructors associated with the class. A constructor with no arguments initializes both the real and imaginary fields to zero. A constructor with a single argument initializes the real field to the given value, and the imaginary value to zero. A constructor with two arguments initializes both real and imaginary fields. Finally, a copy constructor can be used to initialize a complex number with values derived from another complex number.</P>
<UL><PRE>
std::complex&lt;double&gt; com_one; // value 0 + 0i
std::complex&lt;double&gt; com_two(3.14); // value 3.14 + 0i
std::complex&lt;double&gt; com_three(1.5, 3.14) // value 1.5 + 3.14i
std::complex&lt;double&gt; com_four(com_two); // value is also 3.14 + 0i
</PRE></UL>
<P>A complex number can be assigned the value of another complex number. Since the one-argument constructor is also used for a conversion operator, a complex number can also be assigned the value of a real number. The real field is changed to the right-hand side, while the imaginary field is set to zero:</P>
<UL><PRE>
com_one = com_three; // becomes 1.5 + 3.14i
com_three = 2.17; // becomes 2.17 + 0i
</PRE></UL>
<A NAME="idx435"><!></A>
<P>The function <SAMP>polar()</SAMP> can be used to construct a complex number with the given magnitude and phase angle:</P>
<UL><PRE>
com_four = std::polar(5.6, 1.8);
</PRE></UL>
<A NAME="idx436"><!></A>
<P>The conjugate of a complex number is formed using the function <SAMP>conj()</SAMP>. If a complex number represents <SAMP>x + iy</SAMP>, then the conjugate is the value <SAMP>x-iy</SAMP>.</P>
<UL><PRE>
std::complex&lt;double&gt; com_five = std::conj(com_four);
</PRE></UL>
<A NAME="2022"><H3>20.2.2 Accessing Complex Number Values</H3></A>
<A NAME="idx437"><!></A>
<P>The member functions <SAMP>real()</SAMP> and <SAMP>imag()</SAMP> return the real and imaginary fields of a complex number, respectively. These functions can also be invoked as ordinary functions with complex number arguments.</P>
<UL><PRE>
// the following should be the same
std::cout &lt;&lt; com_one.real() &lt;&lt; "+" &lt;&lt; com_one.imag()
&lt;&lt; "i" &lt;&lt; std::endl;
std::cout &lt;&lt; std::real(com_one) &lt;&lt; "+" &lt;&lt; std::imag(com_one)
&lt;&lt; "i" &lt;&lt; std::endl;
</PRE></UL>
<BLOCKQUOTE><HR><B>
NOTE -- With the exception of the member functions real() and imag(), most operations on complex numbers are performed using ordinary functions, not member functions.
</B><HR></BLOCKQUOTE>
<A NAME="2023"><H3>20.2.3 Arithmetic Operations</H3></A>
<P>The arithmetic operators <SAMP>+</SAMP>,<SAMP> -</SAMP>,<SAMP> *</SAMP>, and <SAMP>/</SAMP> can be used to perform addition, subtraction, multiplication, and division of complex numbers. All four work either with two complex numbers, or with a complex number and a real value. Assignment operators are also defined for all four.</P>
<UL><PRE>
std::cout &lt;&lt; com_one + com_two &lt;&lt; std::endl;
std::cout &lt;&lt; com_one - 3.14 &lt;&lt; std::endl;
std::cout &lt;&lt; 2.75 * com_two &lt;&lt; std::endl;
com_one += com_three / 2.0;
</PRE></UL>
<P>The unary operators <SAMP>+</SAMP> and <SAMP>-</SAMP> can also be applied to complex numbers.</P>
<A NAME="2024"><H3>20.2.4 Comparing Complex Values</H3></A>
<A NAME="idx438"><!></A>
<P>Two complex numbers can be compared for equality or inequality, using <SAMP>operator==()</SAMP> and <SAMP>operator!=(). </SAMP>Two values are equal if their corresponding fields are equal. Complex numbers do not have a natural ordering, and thus cannot be compared using any other relational operator.</P>
<A NAME="2025"><H3>20.2.5 Stream Input and Output</H3></A>
<A NAME="idx439"><!></A>
<P>Complex numbers can be written to an output stream, or read from an input stream, using the normal stream I/O conventions. A value is written in parentheses, either as <SAMP>(u)</SAMP> or <SAMP>(u,v)</SAMP>, depending upon whether or not the imaginary value is zero. A value is read as a set of parentheses surrounding two numeric values.</P>
<A NAME="2026"><H3>20.2.6 Norm and Absolute Value</H3></A>
<A NAME="idx440"><!></A>
<P>The function <SAMP>std::norm()</SAMP> returns the norm of the complex number. This is the sum of the squares of the real and imaginary parts. The function <SAMP>std::abs()</SAMP> returns the absolute value, which is the square root of the norm. Note that both are ordinary functions that take the complex value as an argument, not member functions.</P>
<UL><PRE>
std::cout &lt;&lt; std::norm(com_two) &lt;&lt; std::endl;
std::cout &lt;&lt; std::abs(com_two) &lt;&lt; std::endl;
</PRE></UL>
<A NAME="idx441"><!></A>
<P>The directed phase angle of a complex number is yielded by the function <SAMP>std::arg()</SAMP>:</P>
<UL><PRE>
std::cout &lt;&lt; com_four &lt;&lt; " in polar coordinates is "
&lt;&lt; std::arg(com_four) &lt;&lt; " and " &lt;&lt; std::norm(com_four)
&lt;&lt; std::endl;
</PRE></UL>
<A NAME="2027"><H3>20.2.7 Trigonometric Functions</H3></A>
<A NAME="idx442"><!></A>
<P>The trigonometric functions defined for floating point values have all been extended to complex number arguments. These functions are <SAMP>std::sin()</SAMP>, <SAMP>std::cos()</SAMP>, <SAMP>std::tan()</SAMP>, <SAMP>std::sinh()</SAMP>, <SAMP>std::cosh()</SAMP>, and <SAMP>std::tanh()</SAMP>. Each takes a single complex number as argument and returns a complex number as result. </P>
<A NAME="2028"><H3>20.2.8 Transcendental Functions</H3></A>
<A NAME="idx443"><!></A>
<P>The transcendental functions<SAMP> std::exp()</SAMP>, <SAMP>std::log()</SAMP>, <SAMP>std::log10()</SAMP>, and <SAMP>std::sqrt()</SAMP> have been extended to complex arguments. Each takes a single complex number as argument, and returns a complex number as result.</P>
<A NAME="idx444"><!></A>
<P>The C++ Standard Library defines several variations of the exponential function <SAMP>std::pow()</SAMP>. Versions exist to raise a complex number to an integer power, to raise a complex number to a complex power or to a real power, or to raise a real value to a complex power.</P>
<BR>
<HR>
<A HREF="20-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="20-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,64 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Example Program: Roots of a Polynomial</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="20-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="21.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>20.3 Example Program: Roots of a Polynomial</H2>
<A NAME="idx445"><!></A>
<BLOCKQUOTE><HR><B>
NOTE -- This program is in the file complx.cpp.
</B><HR></BLOCKQUOTE>
<P>The roots of a polynomial <IMG SRC="images/stdlibug-SpecialClassesa.gif" WIDTH=128 HEIGHT=29>are given by the formula:</P>
<P><IMG SRC="images/stdlibug-SpecialClasses2.gif" WIDTH=177 HEIGHT=71></P>
<P>The following function takes as input three double precision numbers, and returns the complex roots as a pair of values.</P>
<UL><PRE>
typedef std::complex&lt;double&gt; dcomplex;
std::pair&lt;dcomplex, dcomplex&gt; quadratic
(dcomplex a, dcomplex b, dcomplex c)
// return the roots of a quadratic equation
{
dcomplex root = std::sqrt(b * b - 4.0 * a * c);
a *= 2.0;
return std::make_pair( (-b + root)/a,
(-b - root)/a );
}
</PRE></UL>
<BR>
<HR>
<A HREF="20-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="21.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,58 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>complex</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="19-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="20-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 20: complex</H1>
<UL>
<UL><LI><A HREF="20-1.html">20.1 Overview</A></LI></UL>
<UL><UL><LI><A HREF="20-1.html#2011">20.1.1 Include Files</A></LI></UL></UL>
<UL><LI><A HREF="20-2.html">20.2 Creating and Using Complex Numbers</A></LI></UL>
<UL><UL><LI><A HREF="20-2.html#2021">20.2.1 Declaring Complex Numbers</A></LI></UL></UL>
<UL><UL><LI><A HREF="20-2.html#2022">20.2.2 Accessing Complex Number Values</A></LI></UL></UL>
<UL><UL><LI><A HREF="20-2.html#2023">20.2.3 Arithmetic Operations</A></LI></UL></UL>
<UL><UL><LI><A HREF="20-2.html#2024">20.2.4 Comparing Complex Values</A></LI></UL></UL>
<UL><UL><LI><A HREF="20-2.html#2025">20.2.5 Stream Input and Output</A></LI></UL></UL>
<UL><UL><LI><A HREF="20-2.html#2026">20.2.6 Norm and Absolute Value</A></LI></UL></UL>
<UL><UL><LI><A HREF="20-2.html#2027">20.2.7 Trigonometric Functions</A></LI></UL></UL>
<UL><UL><LI><A HREF="20-2.html#2028">20.2.8 Transcendental Functions</A></LI></UL></UL>
<UL><LI><A HREF="20-3.html">20.3 Example Program: Roots of a Polynomial</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="19-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="20-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,49 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="21.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="21-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>21.1 Overview</H2>
<A NAME="idx446"><!></A>
<P>A feature of the C++ Standard Library is an organized mechanism for describing the characteristics of the fundamental types provided in the execution environment. In older C and C++ libraries, these characteristics were often described by large collections of symbolic constants or macros. For example, the smallest representable value that could be stored in a variable of type <SAMP>char</SAMP> would be found in the constant named <SAMP>CHAR_MIN</SAMP>; the similar constant for a <SAMP>short</SAMP> would be known as <SAMP>SHRT_MIN</SAMP>; a float would be <SAMP>FLT_MIN</SAMP>, and so on. These manifest constants are still available in the headers <SAMP>&lt;climits&gt;</SAMP> and <SAMP>&lt;cfloat&gt;</SAMP>. </P>
<A NAME="idx447"><!></A>
<P>The class template <B><I><A HREF="../stdlibref/numeric-limits.html">numeric_limits</A></I></B> provides a uniform way of representing this information for all numeric types. Instead of using a different symbolic name for each new datatype, the primary class template defines a generic interface in the form of static data members and static member functions. The primary template supplies useless values just so that it can still be used in generic code. It can be distinguished from its specializations by examining the value of the <SAMP>static const bool</SAMP> data member <SAMP>std::numeric_limits&lt;&gt;::is_specialized</SAMP> which will be <SAMP>false</SAMP> for the primary template and <SAMP>true</SAMP> for any specialization. Specializations of this class template then provide a meaningful definition of every member for each fundamental type. For example, the smallest character value is found as the result of invoking the function <SAMP>std::numeric_limits&lt;char&gt;::min()</SAMP>, while the smallest floating point value is found using <SAMP>std::numeric_limits&lt;float&gt;::min()</SAMP>, and so on.</P>
<P>Using a class template not only greatly reduces the number of symbolic names that need to be defined to describe the operating environment, but it also ensures consistency between the descriptions of the various types. Most important, however, it allows programs to treat any object or variable generically, without regard to its specific type. </P>
<P>For the sake of compatibility, the <SAMP>numeric_limits</SAMP> mechanism is used as an addition to the symbolic constants used in older C++ libraries, rather than a strict replacement. Thus both mechanisms exist in parallel for the present. The library provides specializations of <SAMP>numeric_limits</SAMP> for all fundamental types including <SAMP>bool</SAMP> and <SAMP>wchar_t</SAMP>. Users are expected to provide specializations for their own types, such as rational.</P>
<BR>
<HR>
<A HREF="21.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="21-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,80 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Fundamental Datatypes</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="21-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="21-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>21.2 Fundamental Datatypes</H2>
<A NAME="idx448"><!></A>
<A NAME="idx449"><!></A>
<P>The C++ Standard Library describes a specific type by providing a specialization of the<SAMP> numeric_limits</SAMP> template for the type. Static member functions and static constant data members then provide information specific to the type. The C++ Standard Library includes descriptions of the fundamental datatypes given in <A HREF="21-2.html#Table&nbsp;21">Table&nbsp;21</A>.</P>
<H4><A NAME="Table&nbsp;21">Table&nbsp;21: Fundamental datatypes of the C++ Standard Library&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B><SAMP>bool</SAMP></B>
</td><td valign=top><B><SAMP>char</SAMP></B>
</td><td valign=top><B><SAMP>int</SAMP></B>
</td><td valign=top><B><SAMP>float</SAMP></B>
</td></tr>
<tr><td valign=top colspan=1 rowspan=6>&nbsp;
</td><td valign=top><P CLASS="TABLE"><SAMP>signed char</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>short</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>double</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>unsigned char</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>long</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>long double</SAMP></P>
</td></tr>
<tr><td valign=top colspan=1 rowspan=4>&nbsp;
</td><td valign=top><P CLASS="TABLE"><SAMP>wchar_t</SAMP></P>
</td><td valign=top colspan=1 rowspan=4>&nbsp;
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>unsigned short</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>unsigned int</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>unsigned long</SAMP></P>
</td></tr>
</TABLE>
<P>Certain implementations may also provide information on other datatypes. Whether or not an implementation is described can be discovered using the static data member <SAMP>is_specialized</SAMP>. For example, the following is legal, and will indicate that the <B><I><A HREF="../stdlibref/basic-string.html">string</A></I></B> datatype is not described by this mechanism.</P>
<UL><PRE>
std::cout &lt;&lt; "are strings described " &lt;&lt;
std::numeric_limits&lt;string&gt;::is_specialized &lt;&lt; std::endl;
</PRE></UL>
<P>For datatypes that do not have a specialization, the values yielded by the functions and data members in <SAMP>numeric_limits</SAMP> are generally zero or <SAMP>false</SAMP>.</P>
<BR>
<HR>
<A HREF="21-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="21-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,201 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>numeric_limits Members</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="21-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>21.3 numeric_limits Members</H2>
<A NAME="idx450"><!></A>
<P>Since a number of the members in the <SAMP>numeric_limits</SAMP> template specializations are meaningful only for floating point specializations, it is useful to separate the description of the members into <I>common </I>fields and <I>floating-point specific</I> fields.</P>
<A NAME="2131"><H3>21.3.1 Members Common to All Types</H3></A>
<A NAME="idx451"><!></A>
<P><A HREF="21-3.html#Table&nbsp;22">Table&nbsp;22</A> summarizes the information available through the <B><I><A HREF="../stdlibref/numeric-limits.html">numeric_limits</A></I></B> static data members and functions.</P>
<H4><A NAME="Table&nbsp;22">Table&nbsp;22: Information available through numeric_limits&lt;T&gt; </A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Type</B>
</td><td valign=top><B>Name</B>
</td><td valign=top><B>Meaning </B>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>is_specialized</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if a specialization exists, <SAMP>false</SAMP> otherwise </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>min()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Smallest finite value<br>Corresponding constant: <SAMP>XXX_MIN</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>max()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Largest finite value<br>Corresponding constant: <SAMP>XXX_MAX</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>radix</SAMP></P>
</td><td valign=top><P CLASS="TABLE">The base of the representation</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>digits</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Number of <SAMP>radix</SAMP> digits that can be represented without change</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>digits10</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Number of base-10 digits that can be represented without change</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>is_signed</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if the type is signed</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>is_integer</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if the type is integer</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>is_exact</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if the representation is exact</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>is_bounded</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if representation is finite</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>is_modulo</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if adding two positive values of type T can yield a result less than either value</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>traps</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if trapping is implemented for the type</P>
</td></tr>
</TABLE>
<P>In the table above, the <SAMP>XXX</SAMP> prefix is replaced with <SAMP>CHAR</SAMP>, <SAMP>SCHAR</SAMP>, <SAMP>UCHAR</SAMP>, <SAMP>SHRT</SAMP>, <SAMP>USHRT</SAMP>, <SAMP>INT</SAMP>, <SAMP>UINT</SAMP>, <SAMP>LONG</SAMP>, and <SAMP>ULONG</SAMP>, respectively, for the corresponding values of types <SAMP>char</SAMP>, <SAMP>signed char</SAMP>, <SAMP>unsigned char</SAMP>, <SAMP>short</SAMP>, <SAMP>unsigned short</SAMP>, <SAMP>int</SAMP>, <SAMP>unsigned</SAMP>, <SAMP>long</SAMP>, and <SAMP>unsigned long</SAMP>, as appropriate. These manifest constants are defined in the header <SAMP>&lt;climits&gt;</SAMP>. </P>
<P><SAMP>radix</SAMP> represents the internal base for the representation. For example, most machines use a base 2 radix for integer data values; however, some may also support a representation, such as BCD, that uses a different base. The <SAMP>digits</SAMP> member then represents the number of such <SAMP>radix</SAMP> values that can be held in a value. For an integer type, this would be the number of non-sign bits in the representation.</P>
<P>All fundamental types are bounded. However, an implementation might choose to include, for example, an infinite precision integer type that would not be bounded.</P>
<P>A type is <I>modulo</I> if the value resulting from the addition of two positive values can <I>wrap around</I>, that is, be smaller than either argument. The fundamental unsigned integer types are all modulo. Signed integer types are usually modulo. The fundamental floating point types typically are not modulo.</P>
<A NAME="2132"><H3>21.3.2 Members Specific to Floating Point Values</H3></A>
<A NAME="idx452"><!></A>
<P>The members described in <A HREF="21-3.html#Table&nbsp;23">Table&nbsp;23</A> are either specific to floating point values, or have a meaning slightly different for floating point values than the one described earlier for non-floating datatypes.</P>
<H4><A NAME="Table&nbsp;23">Table&nbsp;23: Members specific to floating point values&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Type</B>
</td><td valign=top><B>Name</B>
</td><td valign=top><B>Meaning</B>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>min()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Minimum positive normalized value<br>Corresponding constant: <SAMP>XXX_MIN</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>digits</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Number of digits in the mantissa<br>Corresponding constant: <SAMP>XXX_MANT_DIG</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>radix</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Base (or radix) of the exponent representation<br>Corresponding constant: <SAMP>FLT_RADIX</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>epsilon()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Difference between 1 and the least representable value greater than 1<br>Corresponding constant: <SAMP>XXX_EPSILON</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>round_error()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">A measurement of the rounding error</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>min_exponent</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Minimum negative exponent<br>Corresponding constant: <SAMP>XXX_MIN_EXP</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>min_exponent10</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Minimum value such that 10 raised to that power is in range<br>Corresponding constant: <SAMP>XXX_MIN_10_EXP</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>max_exponent</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Maximum positive exponent<br>Corresponding constant: <SAMP>XXX_MAX_EXP</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>int</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>max_exponent10</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Maximum value such that 10 raised to that power is in range<br>Corresponding constant: <SAMP>XXX_MAX_10_EXP</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>has_infinity</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if the type has a representation of positive infinity</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>infinity()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Representation of infinity, if available<br>Corresponding constant: <SAMP>INFINITY</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>has_quiet_NaN</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if there is a representation of a Quiet \Q\QNot a Number"</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>quiet_NaN()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Representation of Quiet NaN, if available<br>Corresponding constant: <SAMP>NAN</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>has_signaling_NaN</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if there is a representation for a Signaling NaN</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>signaling_NaN()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Representation of Signaling NaN, if available</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>has_denorm</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if the representation allows denormalized values</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>T</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>denorm_min()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Minimum positive denormalized value </P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>is_iec559</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if representation adheres to IEC 559 standard.</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>bool</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>tinyness_before</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>true</SAMP> if <SAMP>tinyness</SAMP> is detected before rounding</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>float_round_style</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>round_style</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Rounding style for type<br>Corresponding constant: <SAMP>FLT_ROUNDS</SAMP></P>
</td></tr>
</TABLE>
<P>In the table above, the <SAMP>XXX</SAMP> prefix is replaced with <SAMP>FLT</SAMP>, <SAMP>DBL</SAMP>, and <SAMP>LDBL</SAMP>, respectively, for the corresponding values of types <SAMP>float</SAMP>, <SAMP>double</SAMP>, and <SAMP>long double</SAMP>. These manifest constants are defined in the header <SAMP>&lt;cfloat&gt;</SAMP>.</P>
<P>A <SAMP>NaN</SAMP> is a <I>Not a Number</I>. It is a set of representable values that nevertheless do not correspond to any numeric quantity. Many numeric algorithms manipulate such values. NANs are typically returned by numeric algorithms to indicate a result that is outside of the domain of the data type. For instance, the operations <SAMP>0.0/0.0</SAMP> or <SAMP>0 * std::numeric_limits&lt;double&gt;::infinity()</SAMP> yield NAN or <SAMP>std::numeric_limits&lt;double&gt;::quiet_NaN()</SAMP>. NANs come in two flavors: quiet and signaling. A quiet NAN can be safely used in computations without the danger of triggering an exception. A signaling NAN can be copied, assigned, and compared without causing an exception; however, using it in an arithmetic expression triggers a hardware exception. A unique property of all NANs is that they do not compare equal to any number, including another NAN.</P>
<P>The IEC 559 standard is a standard approved by the International Electrotechnical Commission. It is the same as the IEEE standard 754. The standard precisely specifies the representation, many properties, and relationships of the fundamental floating point types. </P>
<P>The value returned by the member function <SAMP>round_style()</SAMP> is one of the following: <SAMP>round_indeterminate</SAMP>, <SAMP>round_toward_zero</SAMP>, <SAMP>round_to_nearest</SAMP>, <SAMP>round_toward_infinity</SAMP>, or <SAMP>round_toward_neg_infinity</SAMP>.</P>
<BR>
<HR>
<A HREF="21-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,51 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>numeric_limits</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="20-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="21-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 21: numeric_limits</H1>
<UL>
<UL><LI><A HREF="21-1.html">21.1 Overview</A></LI></UL>
<UL><LI><A HREF="21-2.html">21.2 Fundamental Datatypes</A></LI></UL>
<UL><LI><A HREF="21-3.html">21.3 numeric_limits Members</A></LI></UL>
<UL><UL><LI><A HREF="21-3.html#2131">21.3.1 Members Common to All Types</A></LI></UL></UL>
<UL><UL><LI><A HREF="21-3.html#2132">21.3.2 Members Specific to Floating Point Values</A></LI></UL></UL>
</UL>
<BR>
<HR>
<A HREF="20-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="21-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,151 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Overview</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="22.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>22.1 Overview</H2>
<P>The C++ language is often used in scientific and engineering work to perform long and difficult operations on arrays of numbers. While the language itself provides the flexibility and efficiency needed for these kind of calculations, the code can become very complex. Naturally, we can use the object-oriented features of the language to encapsulate this complexity, but classes designed to simplify numeric programming without sacrificing performance are notoriously difficult to code correctly. Fortunately, the C++ Standard Library now provides some relief in the form of the <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> class template. </P>
<A NAME="idx453"><!></A>
<P>This class template provides the necessary efficiency in the form of a single-dimensional array. Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> can be used to perform calculations directly on arrays in a single dimension, and to represent higher order arrays with a little more effort. An extended set of subscripting operators provides the basis for building matrices and other more sophisticated classes from the relatively simple and lean <B><I>valarray</I></B>.</P>
<A NAME="2211"><H3>22.1.1 Performance Issues</H3></A>
<A NAME="idx454"><!></A>
<P>Since efficiency is such an important concern in numeric programming, the <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> class addresses performance in several ways. </P>
<P>First of all, <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> is designed to give compilers maximum latitude in optimizing operations within the class. This is achieved primarily by avoiding any aliasing of elements within a <B><I>valarray</I></B>. This means that every element in a given <B><I>valarray</I></B> is located at its own unique memory address, exactly as it would be in an ordinary array. While this prevents a <B><I>valarray</I></B> implementation from using certain kinds of optimizations, such as aliasing all elements with default values to a single stored value, that loss is more than compensated by a competent optimizer's ability to streamline operations on the array. </P>
<P>Secondly, the <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> class uses internal optimization templates to ensure that the most efficient method is used to copy data whenever possible. This optimization is possible in part because of the restriction on aliasing.</P>
<P>Lastly, the <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> class imposes certain requirements on any type used with it. Most of these restrictions are not related to performance; they are simply necessary to allow generalized numeric operations. But one in particular, initialization semantics, exists at least in part to allow optimizations. A summary of these restrictions follows.</P>
<A NAME="2212"><H3>22.1.2 Type Restrictions</H3></A>
<A NAME="idx455"><!></A>
<P>A <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> can be instantiated only on a type <SAMP>T</SAMP> meeting the following requirements:</P>
<OL>
<LI><P CLASS="LIST">A type <SAMP>T</SAMP> must not be an abstract class.</P></LI>
<LI><P CLASS="LIST">A type <SAMP>T</SAMP> cannot be a reference type; that is, <SAMP>std::valarray&lt;int&amp;&gt;</SAMP> is not allowed.</P></LI>
<LI><P CLASS="LIST">A type <SAMP>T</SAMP> must not be const or volatile qualified; in other words,<SAMP> std::valarray&lt;const&nbsp;int&gt;</SAMP> is not allowed.</P></LI>
<LI><P CLASS="LIST">A type <SAMP>T</SAMP> must not overload unary <SAMP>operator&amp;</SAMP>.</P></LI>
<LI><P CLASS="LIST">A type <SAMP>T</SAMP> must not throw exceptions.</P></LI>
<LI><P CLASS="LIST">If a type <SAMP>T</SAMP> is a class it must have a public default constructor, a public copy constructor with the signature <SAMP>T::T(const T&amp;)</SAMP>, and a public destructor.</P></LI>
<LI><P CLASS="LIST">If a type <SAMP>T</SAMP> is a class, it must have a public assignment operator with a signature matching one of the following: <SAMP>T&amp; T::operator=(const T&amp;) </SAMP>or <SAMP>T&amp; T::operator=(T)</SAMP>.</P></LI>
<LI><P CLASS="LIST">If a type <SAMP>T</SAMP> is a class, then its default constructor, copy constructor, and assignment operator must behave in such a way that there is no difference between default construction followed by assignment, and copy construction. Additionally, destruction of an object followed by copy construction must be equivalent to assignment. </P></LI>
<P CLASS="LIST">Here is a summary of the necessary relationship between copy construction and assignment, where <SAMP>T</SAMP> is the type, <SAMP>t</SAMP> and <SAMP>v</SAMP> are instances of the type, and <SAMP>p</SAMP> is a pointer to an instance of the type:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE"><SAMP>T t(), t = v</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><I>is semantically equivalent to:</I></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>T t(v)</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>new (p) T(), *p = v</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><I>is semantically equivalent to:</I></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>new (p) T(v)</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>p-&gt;~T(), new (p) T(v)</SAMP></P>
</td><td valign=top><P CLASS="TABLE"><I>is semantically equivalent to:</I></P>
</td><td valign=top><P CLASS="TABLE"><SAMP>*p = v</SAMP></P>
</td></tr>
</TABLE>
<P CLASS="LIST">This summary demonstrates that there is nothing subtle and clever happening in the process of copy construction or assignment. This consistency is particularly important for portability, since any implementation of <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> can expect that these operations have the described equivalency even if a particular implementation may not care.</P>
</OL>
<A NAME="2212-1"><H4>22.1.2.1 A Class That Meets the Type Restrictions</H4></A>
<A NAME="idx456"><!></A>
<P>All the built-in numeric types, like <SAMP>int</SAMP>, <SAMP>long</SAMP>, <SAMP>float</SAMP>, and so on, clearly meet the type requirements for <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B>. Here is an example of a minimalist class that does, too. This class is simple enough that the compiler generated constructors, destructor, and assignment operator would actually suffice. As you can see, there is nothing very special needed here. Rather, it is the absence of something special that the requirements guard against.</P>
<UL><PRE>
class Num
{
int val_;
public:
Num() : val_(0) {} // public default constructor
Num(const Num&amp; n):val_(n.val()) {} // public copy constructor
~Num() {} // public destructor
Num&amp; operator=(const Num&amp; n) // public assignment
{
val-_ = n.val();
return *this;
}
int val() const { return val_; }
int val(int v)
{
int tmp = val_;
val_ = v;
return tmp;
}
};
</PRE></UL>
<A NAME="2212-2"><H4>22.1.2.2 A Class That Doesn't Meet the Type Restrictions</H4></A>
<A NAME="idx457"><!></A>
<P>Now let's look at a small variation on the <B><I>Num</I></B> class that does not meet the type requirements for class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B>. Depending on how this class is used, it may or may not be a problem in a <B><I>valarray</I></B>, but it most definitely violates the requirements since default construction followed by assignment may result in a different state than copy construction.</P>
<UL><PRE>
class Num
{
bool assigned_;
int val_;
public:
Num(): val_(0), assigned_(false) {} // public default constructor
Num(const Num&amp; n) // public copy constructor
: val_(n.val()), assigned_(n.assigned()) {}
~Num() {} // public destructor
Num&amp; operator=(const Num&amp; n) // public assignment
{
val_ = n.val();
assigned_ = true; // Whoops, violates rule 8 if
// n.assigned() == false.
return *this;
}
int val() const { return val_; }
int val(int v)
{
int tmp = val_;
val_ = v;
return tmp;
}
bool assigned() const { return assigned; }
};
</PRE></UL>
<A NAME="2213"><H3>22.1.3 Other Unique Features</H3></A>
<P>It is important to note that operations not defined for a particular type are not available for a <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> of that type. For instance, if a type does not have ordering operations, as is the case with the standard <B><I><A HREF="../stdlibref/complex.html">complex</A></I></B> class template, then those ordering operands are not available in a <B><I>valarray</I></B> of that type.</P>
<A NAME="idx458"><!></A>
<P>Another important feature is that, along with the <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> class, the <B><I>valarray</I></B> header defines several auxiliary classes to support extended subset operations. These are <SAMP>slice</SAMP>, <SAMP>gslice</SAMP>, <SAMP>slice_array</SAMP>, <SAMP>gslice_array</SAMP>, <SAMP>indirect_array</SAMP>, and <SAMP>mask_array</SAMP>, which are explained in <A HREF="22-4.html#2242">Section&nbsp;22.4.2</A> and its subsections. For now we'll just note that <SAMP>slice</SAMP> and <SAMP>gslice</SAMP> are used to define the parameters of a BLAS-like slice, or a generalized slice into an array. The remainder of these auxiliary classes define the types returned by subset operations. None of these can be instantiated directly by a program since they lack public constructors.</P>
<A NAME="2214"><H3>22.1.4 Header Files</H3></A>
<A NAME="idx459"><!></A>
<P>Programs that use <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B>s must include the <SAMP>valarray</SAMP> header file:</P>
<UL><PRE>
#include &lt;valarray&gt;
</PRE></UL>
<BR>
<HR>
<A HREF="22.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,67 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Declaring a valarray</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="22-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>22.2 Declaring a valarray</H2>
<A NAME="idx460"><!></A>
<P>A <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> can be constructed by any of the following means:</P>
<UL>
<LI><P CLASS="LIST"><B>Default constructor</B>. The default constructor is provided to allow arrays of <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B>s. Use the resize function to adjust the <B><I>valarray</I></B> after construction.</P></LI>
<LI><P CLASS="LIST"><B>Construction and initialization.</B> A <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> provides two ways to start with a given size and values: </P></LI>
<UL>
<LI><P CLASS="LIST"><SAMP>valarray(const T&amp; v,size_t n)</SAMP> constructs a <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> of size <SAMP>n</SAMP> with each element initialized to the value <SAMP>v</SAMP>. </P></LI>
<LI><P CLASS="LIST"><SAMP>valarray(const T* p,size_t n)</SAMP> constructs a <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> of size <SAMP>n</SAMP> with each element initialized to the corresponding element of the array pointed to by <SAMP>p</SAMP>. This constructor allows a program to transfer data with maximum efficiency from an ordinary `C' array (resulting from a file operation, for example) into a <B><I>valarray</I></B>.</P></LI>
</UL>
<LI><P CLASS="LIST"><B>Copy constructor</B>. The copy constructor has value semantics.</P></LI>
<LI><P CLASS="LIST"><B>Conversion constructors</B>. Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> provides four conversion constructors for converting from auxiliary classes generated by subscript operations. We'll look at these classes in detail and describe the use of the conversion constructors in <A HREF="22-4.html#2242">Section&nbsp;22.4.2</A>.</P></LI>
</UL>
<P>The following example shows the use of the first three categories of constructors:</P>
<UL><PRE>
#include &lt;valarray&gt;
std::valarray&lt;int&gt; v1; // construct an empty valarray
std::valarray&lt;int&gt; v2(1,3); // construct a valarray of three
// elements, all initialized to 1
v1.resize(3,2); // resize the first valarray to three
// elements, all initialized to 2
std::valarray&lt;int&gt; v3(v1); // v3 gets a copy of v1's elements.
</PRE></UL>
<BR>
<HR>
<A HREF="22-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,46 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Assignment Operators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="22-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>22.3 Assignment Operators</H2>
<A NAME="idx461"><!></A>
<P>Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> provides six assignment operations. These are: assignment from another <B><I>valarray</I></B>, assignment from a <SAMP>T</SAMP> value, and assignment from any of the four auxiliary classes returned by the subset operations.</P>
<P>Assignment from a <SAMP>T</SAMP> value assigns that value to all elements in the <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B>. Assignment from another <B><I>valarray</I></B> or any of the auxiliary classes assigns corresponding elements from the one to the other. In any case, the left- and right-hand- side arrays must be equal in length.</P>
<BR>
<HR>
<A HREF="22-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,142 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Element and Subset Access</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="22-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-5.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>22.4 Element and Subset Access</H2>
<A NAME="2241"><H3>22.4.1 Ordinary Index Operators</H3></A>
<A NAME="idx462"><!></A>
<P>Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> provides <SAMP>const</SAMP> and non-<SAMP>const</SAMP> versions of <SAMP>operator[](size_t)</SAMP>. The const version returns the value of the indicated index, while the non-const version returns a reference to the value.</P>
<P>For example, continuing the example from <A HREF="22-2.html">Section&nbsp;22.2</A>:</P>
<UL><PRE>
v1[2] = 5; // change the element at position 2 using
// the non-const index operator
</PRE></UL>
<A NAME="2242"><H3>22.4.2 Subset Operators</H3></A>
<A NAME="idx463"><!></A>
<P>Along with the ordinary subscript operators, <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> provides four different subset operations. Each of these also has both <SAMP>const</SAMP> and non-<SAMP>const</SAMP> versions. The <SAMP>const</SAMP> version always returns a new <B><I>valarray</I></B> initialized with data appropriate to the subset operation. The non-<SAMP>const</SAMP> version returns an auxiliary array class that references directly the data in the original <B><I>valarray</I></B>. Thus each non-<SAMP>const</SAMP> version provides a view into the original array by which specific elements may be accessed. Note that an instance of any of these auxiliary classes can only be obtained from the operator. A program cannot instantiate one of these classes directly as they lack a public constructor.</P>
<P>The four subset operations are the <SAMP>slice</SAMP> operation, the <SAMP>gslice</SAMP> operation, the <SAMP>mask</SAMP> operation, and the <SAMP>indirect</SAMP> operation. Both <SAMP>slice</SAMP> and <SAMP>gslice</SAMP> use a special auxiliary class to specify the intent of the operation. These classes are called <B><I><A HREF="../stdlibref/slice.html">slice</A></I></B> and <B><I><A HREF="../stdlibref/gslice.html">gslice</A></I></B> respectively. </P>
<A NAME="2242-1"><H4>22.4.2.1 The Slice Operation</H4></A>
<A NAME="idx464"><!></A>
<P>The <SAMP>slice</SAMP> operation provides a view into a <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> that is like the same operation defined in Basic Linear Algebra Subprograms (BLAS). A <I>slice</I> is defined by a starting index, a length, and a stride. To call the <SAMP>slice</SAMP> subscript operator, a program passes a <B><I><A HREF="../stdlibref/slice.html">slice</A></I></B> object initialized with a constructor taking these three parameters: <SAMP>std::slice(size_t start, size_t length, size_t stride)</SAMP>. The returned array consists only of length elements, starting with the element at the starting index and continuing with each element's stride steps after the previously selected one. The following example illustrates this process:</P>
<UL><PRE>
using std::slice;
int a[9] = {1,2,3,4,5,6,7,8,9};
valarray&lt;int&gt; all(a,9); //all = {1,2,3,4,5,6,7,8,9}
valarray&lt;int&gt; odd = all[slice(0,5,2)]; //odd = {1,3,5,7,9}
</PRE></UL>
<P>In this example, the subscript operation actually returns a <B><I><A HREF="../stdlibref/slice-array.html">slice_array</A></I></B>. Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> contains conversion constructors for this class as well as the auxiliary classes returned by other subset operations. Note, however, that the reference semantics are lost in the conversion since odd is an entirely new array. Class <B><I>slice_array</I></B> and the other auxiliary classes exist only to help in the selection of a view and the creation of a new <B><I>valarray</I></B> based on that view.</P>
<A NAME="2242-2"><H4>22.4.2.2 The gslice Operation</H4></A>
<A NAME="idx465"><!></A>
<P>The <SAMP>gslice</SAMP> operation differs from the <SAMP>slice</SAMP> in that it defines a set of strides and an associated set of lengths. This set of lengths and strides allows a program to treat a single-dimensional <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> as a multidimensional array and to pull multi-dimensional slices from that array. Note that the <SAMP>gslice</SAMP> subset operator takes a <SAMP>gslice</SAMP> argument and returns a <B><I><A HREF="../stdlibref/gslice-array.html">gslice_array</A></I></B> in the same manner that the <SAMP>slice</SAMP> operation takes a <B><I><A HREF="../stdlibref/slice.html">slice</A></I></B> and returns a <B><I><A HREF="../stdlibref/slice-array.html">slice_array</A></I></B>.</P>
<P>Here is a simple example that uses <B><I><A HREF="../stdlibref/gslice.html">gslice</A></I></B>s to represent a three-dimensional array. In this example, the first three numbers form the top row of a two-dimensional array whose center and bottom rows are completed with the next six numbers. The next nine numbers represent the second or <I>middle</I> two-dimensional array, and the last nine the <I>back</I> two-dimensional array. Taken together they form a three- dimensional <I>cube</I>. See the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A> for an extended version of this example that uses additional <B><I>gslice</I></B>s to pull <B><I><A HREF="../stdlibref/slice.html">slice</A></I></B>s along several different axes of the three-dimensional cube defined by this first slice.</P>
<UL><PRE>
using std::gslice;
using std::valarray;
int a[27] = {0,1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9,10};
size_t lengths[2] = {3,3};
size_t strides[2] = {3,1};
valarray&lt;int&gt; v(a,27); // initial valarray
valarray&lt;size_t&gt; len(lengths,2); // valarray of lengths
valarray&lt;size_t&gt; stride(strides,2); // valarray of strides
valarray&lt;int&gt; v2(0,9); // valarray to hold the
// generalized slice
v2 = (v[gslice(0,len,stride)]); // slice off the front =
// {0,1,2,3,4,5,6,7,8}
v2 = (v[gslice(9,len,stride)]); // slice off the middle
// = {1,2,3,4,5,6,7,8,9}
Back two-dimensional array = 2 3 4
5 6 7
8 9 10
Middle two-dimensional array = 1 2 3
4 5 6
7 8 9
Front two-dimensional array = 0 1 2
3 4 5
6 7 8
</PRE></UL>
<A NAME="2242-3"><H4>22.4.2.3 Boolean Mask</H4></A>
<A NAME="idx466"><!></A>
<P>The third operation is a boolean <SAMP>mask</SAMP>, which selects certain elements of a <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> based on whether or not the corresponding element of a boolean <B><I>valarray</I></B> is set to <SAMP>true</SAMP>. The size of the boolean <B><I>valarray</I></B> must equal the size of the subscripted <B><I>valarray</I></B>. Like the <B><I><A HREF="../stdlibref/slice.html">slice</A></I></B> example, the following code snippet also selects all the odd numbers in <B><I>all</I></B>. Note that the operation actually returns a <B><I><A HREF="../stdlibref/mask-array.html">mask_array</A></I></B>.</P>
<UL><PRE>
int a[9] = {1,2,3,4,5,6,7,8,9};
std::valarray&lt;int&gt; all(a,9); // all = {1,2,3,4,5,6,7,8,9}
bool b[9]= {true,false,true,false,true,false,true,false,true};
std::valarray&lt;bool&gt; vb(b,9);
std::valarray&lt;int&gt; odd2 = all[vb]; // odd2 = {1,3,5,7,9}
</PRE></UL>
<A NAME="2242-4"><H4>22.4.2.4 Indirect Operation</H4></A>
<A NAME="idx467"><!></A>
<P>Finally, the <SAMP>indirect</SAMP> operation selects elements of a <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> dependent on whether or not a given index is present in a <B><I>valarray</I></B> of <B><I>size_t</I></B>. For instance, if we use <B><I>valarray&lt;size_t&gt;()</I></B> as our subscripting argument, then we select <SAMP>0</SAMP> elements, returning a <B><I>valarray</I></B> or <B><I><A HREF="../stdlibref/indirect-array.html">indirect_array</A></I></B> (if the sub-scripted array is <SAMP>const</SAMP>) of <SAMP>0</SAMP> elements. On the other hand, if we use <B><I>valarray&lt;size_t&gt;(3,1)</I></B>, we select only the third element, thus returning a <B><I>valarray</I></B> or indirect array of <SAMP>1</SAMP> element. Once again, the following example selects all odd-valued elements from <B><I>all</I></B>:</P>
<UL><PRE>
int a[9] = {1,2,3,4,5,6,7,8,9};
std::valarray&lt;int&gt; all(a,9); // all = {1,2,3,4,5,6,7,8,9}
std::size_t c[5] = {0,2,4,6,8};
std::valarray&lt;size_t&gt; in(c,5);
std::valarray&lt;int&gt; oddity = all[in]; // oddity = {1,3,5,7}
</PRE></UL>
<A NAME="idx468"><!></A>
<P>Each of the auxiliary array classes, <B><I><A HREF="../stdlibref/slice-array.html">slice_array</A></I></B>, <B><I><A HREF="../stdlibref/gslice-array.html">gslice_array</A></I></B>, <B><I><A HREF="../stdlibref/mask-array.html">mask_array</A></I></B>, and <B><I><A HREF="../stdlibref/indirect-array.html">indirect_array</A></I></B>, has a set of arithmetic and logical computed assignment operators that when applied affect the selected elements in the original non-<SAMP>const</SAMP> array. In each case, these operators take a <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> as a parameter. Since the <B><I>valarray</I></B> itself contains conversion constructors for each of the auxiliary classes, these arithmetic and logical operators can be applied freely across <B><I>valarray</I></B> objects and auxiliary classes and between the auxiliary classes. Note, however, that reference semantics are lost in the conversion from auxiliary class to <B><I>valarray</I></B>. A <B><I>valarray</I></B> never references data in another <B><I>valarray</I></B>, reference-counting optimization notwithstanding.</P>
<A NAME="2243"><H3>22.4.3 Unary Operators</H3></A>
<A NAME="idx469"><!></A>
<P>Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> provides four unary operations: <SAMP>operator+()</SAMP>, <SAMP>operator-()</SAMP>, <SAMP>operator~(),</SAMP> and <SAMP>operator!()</SAMP>. These operators are not available for types for which they are not defined. Each operator returns a new valarray with the result of applying the operation to each element of the original. For instance, the following negates all values in a <B><I>valarray</I></B>.</P>
<UL><PRE>
float a[4] = {1.0, -2.3, -4.5, 9.0};
std::valarray&lt;float&gt; v(a,4);
std::valarray&lt;float&gt; neg = -v; // neg = {-1.0, 2.3, 4.5, -9.0}
</PRE></UL>
<BR>
<HR>
<A HREF="22-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-5.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,53 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Computed Assignment Operators</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="22-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-6.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>22.5 Computed Assignment Operators</H2>
<A NAME="idx470"><!></A>
<P>Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> offers two different versions of the following operators: <SAMP>operator*=()</SAMP>, <SAMP>operator/=()</SAMP>, <SAMP>operator%=()</SAMP>, <SAMP>operator+=()</SAMP>, <SAMP>operator-=()</SAMP>, <SAMP>operator^=()</SAMP>, <SAMP>operator&amp;=()</SAMP>, <SAMP>operator|=()</SAMP>, <SAMP>operator&lt;&lt;=()</SAMP>, and <SAMP>operator&gt;&gt;=()</SAMP>. In each case, one version takes a <B><I>valarray</I></B> reference and the second takes a <SAMP>T&amp;</SAMP>. The first version of each operation applies its operation to the corresponding elements of self and the <B><I>valarray</I></B> argument. The second version applies the operation to all elements of self using the <SAMP>T&amp;</SAMP> argument. For example:</P>
<UL><PRE>
std::valarray&lt;long&gt; v1(1,3); // v1 = {1,1,1}
std::valarray&lt;long&gt; v2(2,3); // v2 = {2,2,2}
v1 += v2; // v1 = {3,3,3}
v2 += 2; // v2 = {4,4,4}
</PRE></UL>
<BR>
<HR>
<A HREF="22-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-6.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,55 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Member Functions</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="22-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-7.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>22.6 Member Functions</H2>
<A NAME="idx471"><!></A>
<P>The member functions of class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> include the <SAMP>size()</SAMP> function, which returns the size of a <B><I>valarray</I></B>, and the <SAMP>sum()</SAMP> function, which returns the sum of all elements in a <B><I>valarray</I></B>. The functions <SAMP>min()</SAMP> and <SAMP>max()</SAMP> return, respectively, the minimum and maximum values in a <B><I>valarray</I></B>.</P>
<P>Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> also contains two shift functions. Both functions shift elements a specified number of steps to the left, where the <SAMP>0</SAMP><SUP>th</SUP> element is defined as the leftmost. The <SAMP>shift()</SAMP> function fills in at the right with <SAMP>0</SAMP>s or <SAMP>T()</SAMP>s. The <SAMP>cshift()</SAMP> function performs a circular shift or <I>rotation</I> so that the <SAMP>i</SAMP><SUP>th</SUP> element becomes the element at location <SAMP>self.length() - n - i</SAMP>, where <SAMP>i</SAMP> runs from <SAMP>0</SAMP> to <SAMP>n</SAMP>, and <SAMP>n</SAMP> is the number of steps to shift. Both functions return a new <B><I>valarray</I></B>, but the original is not changed. For example:</P>
<UL><PRE>
int a[5] = {1,2,3,4,5};
std::valarray&lt;int&gt; v(a,5);
std::valarray&lt;int&gt; v2 = v.shift(2); // v2 = {3,4,5,0,0}
v2 = v.cshift(2); // v2 = {3,4,5,1,2}
</PRE></UL>
<P>Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> provides two versions of the <SAMP>apply()</SAMP> function. These functions apply a user-specified function to each element in the array. Again, these return a new array with the result leaving the original array unaltered.</P>
<P>Finally, as we noted in the discussion on constructors, <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> has a resize function that allows a program to change the number of elements contained by that array. The original elements, if any, are lost in the process since the function re-initializes all elements in the newly-sized array.</P>
<BR>
<HR>
<A HREF="22-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-7.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,73 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Non-Member Functions</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="22-6.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="VII.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>22.7 Non-Member Functions</H2>
<A NAME="2271"><H3>22.7.1 Binary Operators</H3></A>
<A NAME="idx472"><!></A>
<P>Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> provides a large block of binary operators that allow a program to apply these operators to two <B><I>valarray</I></B>s or to a <B><I>valarray</I></B> and a <SAMP>T</SAMP> value, where the <SAMP>T</SAMP> can occur on the left- or right-hand side of the expression. As you'd expect, these operators do not modify either of their arguments, but instead return a new <B><I>valarray</I></B> containing the result of the operation. Each version that takes two <B><I>valarray</I></B> arguments returns the result of applying the operation to the corresponding elements of the arrays. The versions with a <SAMP>T&amp;</SAMP> argument return a <B><I>valarray</I></B> whose elements result from applying the operation to each element in the <B><I>valarray</I></B> argument along with the <SAMP>T&amp;</SAMP> argument. See the <B><I>valarray</I></B> entry in the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A> for a complete list of binary operators.</P>
<P>Arithmetic and bitwise operators return a <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> of <SAMP>T</SAMP>. Logical operators return a <B><I>valarray&lt;bool&gt;</I></B>, where each element represents the comparison of corresponding elements in two <B><I>valarray</I></B>s or the comparison of each element in an array with a particular value. For example:</P>
<UL><PRE>
int a[3] = {1,2,3};
int b[3] = {0,1,4};
std::valarray&lt;int&gt; v1(a,3);
std::valarray&lt;int&gt; v2(b,3);
std::valarray&lt;int&gt; v3(0,3);
std::valarray&lt;bool&gt; v4(false,3);
v3 = v1 + v2; // v3 = {1,3,7}
v4 = v1 == v2; // v4 = {false,false,false}
v4 = v1 &lt; v2; // v4 = {false,false,true}
</PRE></UL>
<A NAME="2272"><H3>22.7.2 Transcendental Functions</H3></A>
<A NAME="idx473"><!></A>
<P>Class <B><I><A HREF="../stdlibref/valarray.html">valarray</A></I></B> also provides 20 transcendental functions, four of which are overloads. Each function returns a new <B><I>valarray</I></B> that contains elements resulting from the application of the transcendental function to each element in the <B><I>valarray</I></B> passed as an argument. See the <B><I>valarray</I></B> entry in the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A> for a complete list of transcendental functions. </P>
<P>The following example squares each of the elements of an array:</P>
<UL><PRE>
using std::pow;
float a[3] = {2.0, 4.0, 16.0};
std::valarray&lt;float&gt; v(a,3); // v = {2.0, 4.0, 16.0}
std::valarray&lt;float&gt; v2(0.0,3); // v2 = {0.0, 0.0, 0.0}
v2 = std::pow(v,2.0); // v2 = {4.0, 16.0, 256.0 }
</PRE></UL>
<BR>
<HR>
<A HREF="22-6.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="VII.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,68 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>valarray</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="21-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 22: valarray</H1>
<UL>
<UL><LI><A HREF="22-1.html">22.1 Overview</A></LI></UL>
<UL><UL><LI><A HREF="22-1.html#2211">22.1.1 Performance Issues</A></LI></UL></UL>
<UL><UL><LI><A HREF="22-1.html#2212">22.1.2 Type Restrictions</A></LI></UL></UL>
<UL><UL><UL><LI><A HREF="22-1.html#2212-1">22.1.2.1 A Class That Meets the Type Restrictions</A></LI></UL></UL></UL>
<UL><UL><UL><LI><A HREF="22-1.html#2212-2">22.1.2.2 A Class That Doesn't Meet the Type Restrictions</A></LI></UL></UL></UL>
<UL><UL><LI><A HREF="22-1.html#2213">22.1.3 Other Unique Features</A></LI></UL></UL>
<UL><UL><LI><A HREF="22-1.html#2214">22.1.4 Header Files</A></LI></UL></UL>
<UL><LI><A HREF="22-2.html">22.2 Declaring a valarray</A></LI></UL>
<UL><LI><A HREF="22-3.html">22.3 Assignment Operators</A></LI></UL>
<UL><LI><A HREF="22-4.html">22.4 Element and Subset Access</A></LI></UL>
<UL><UL><LI><A HREF="22-4.html#2241">22.4.1 Ordinary Index Operators</A></LI></UL></UL>
<UL><UL><LI><A HREF="22-4.html#2242">22.4.2 Subset Operators</A></LI></UL></UL>
<UL><UL><UL><LI><A HREF="22-4.html#2242-1">22.4.2.1 The Slice Operation</A></LI></UL></UL></UL>
<UL><UL><UL><LI><A HREF="22-4.html#2242-2">22.4.2.2 The gslice Operation</A></LI></UL></UL></UL>
<UL><UL><UL><LI><A HREF="22-4.html#2242-3">22.4.2.3 Boolean Mask</A></LI></UL></UL></UL>
<UL><UL><UL><LI><A HREF="22-4.html#2242-4">22.4.2.4 Indirect Operation</A></LI></UL></UL></UL>
<UL><UL><LI><A HREF="22-4.html#2243">22.4.3 Unary Operators</A></LI></UL></UL>
<UL><LI><A HREF="22-5.html">22.5 Computed Assignment Operators</A></LI></UL>
<UL><LI><A HREF="22-6.html">22.6 Member Functions</A></LI></UL>
<UL><LI><A HREF="22-7.html">22.7 Non-Member Functions</A></LI></UL>
<UL><UL><LI><A HREF="22-7.html#2271">22.7.1 Binary Operators</A></LI></UL></UL>
<UL><UL><LI><A HREF="22-7.html#2272">22.7.2 Transcendental Functions</A></LI></UL></UL>
</UL>
<BR>
<HR>
<A HREF="21-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="22-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,50 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Defining the Terms</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="23.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="23-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>23.1 Defining the Terms</H2>
<P>Computer users all over the world prefer to interact with their systems using their own local languages and cultural conventions. As a developer aiming for high international acceptance of your products, you need to provide users the flexibility for modifying input and output conventions to comply with local requirements, such as different currency and numeric representations. You must also provide the capability for translating interfaces and messages without necessitating many different language versions of your software.</P>
<A NAME="idx474"><!></A>
<P>Two processes that enhance software for worldwide use are <I>internationalization</I> and <I>localization</I>. <I>Internationalization</I> is the process of building into software the potential for worldwide use. It is the result of efforts by programmers and software designers during software development. </P>
<P>Internationalization requires that developers consciously design and implement software for adaptation to various languages and cultural conventions, and avoid hard-coding elements that can be localized, like screen positions and file names. For example, developers should never embed in their code any messages, prompts, or other kind of displayed text, but rather store the messages externally, so they can be translated without requiring the program to be recompiled. A developer of internationalized software should never assume specific conventions for formatting numeric or monetary values, or for displaying date and time.</P>
<A NAME="idx475"><!></A>
<P><I>Localization</I> is the process of actually adapting internationalized software to the needs of users in a particular geographical or cultural area. It includes translation of messages by software translators. It requires the creation and availability of appropriate tables containing relevant local data for use in a given system. This typically is the function of system administrators and operating system vendors, who build facilities for these functions into the program execution environment. Users of internationalized software are involved in the process as well, when they select the local conventions they prefer from the set of conventions available in their environment.</P>
<P>The C++ Standard Library offers a number of classes that support internationalization of your programs. We describe them in detail in this chapter. Before we do, however, we would like to survey some of the cultural conventions that impact software internationalization, and are supported by the programming languages C and C++ and their respective standard libraries. Of course, there are many issues outside our list that need to be addressed, like orientation, sizing and positioning of screen displays, vertical writing and printing, selection of font tables, handling international keyboards, and so on. But let us begin here.</P>
<BR>
<HR>
<A HREF="23.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="23-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,230 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Localizing Cultural Conventions</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="23-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="23-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>23.2 Localizing Cultural Conventions</H2>
<P>The need for localizing software arises from differences in cultural conventions. These differences involve: language itself; representation of numbers and currency; display of time and date; and ordering and classification of characters and strings.</P>
<A NAME="2321"><H3>23.2.1 Language</H3></A>
<A NAME="idx476"><!></A>
<P>Of course, <I>language</I> itself varies from country to country, and even within a country. Your program may require output messages in English, Deutsche, Fran<SAMP>&ccedil;</SAMP>ais, Italiano, or any number of languages commonly used in the world today.</P>
<A NAME="idx477"><!></A>
<P>Languages may also differ in the <I>alphabet</I> they use. Examples of different languages with their respective alphabets are given below:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">American English:</P>
</td><td valign=top><P CLASS="TABLE"><SAMP>a-z</SAMP>, <SAMP>A-Z</SAMP>, and punctuation</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">German:</P>
</td><td valign=top><P CLASS="TABLE"><SAMP>a-z</SAMP>, <SAMP>A-Z</SAMP>, punctuation, and <SAMP>&auml;&ouml;&uuml; &Auml;&ouml;&Uuml; &#223;</SAMP></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">Greek:</P>
</td><td valign=top><P CLASS="TABLE"><IMG SRC="images/alpha.gif">-<IMG SRC="images/omega.gif">, <IMG SRC="images/capalpha.gif">-<IMG SRC="images/capomega.gif">, and punctuation</P>
</td></tr>
</TABLE>
<A NAME="2322"><H3>23.2.2 Numbers</H3></A>
<A NAME="idx478"><!></A>
<P>The representation of <I>numbers </I>depends on local customs, which vary from country to country. For example, consider the <I>radix character</I>, the symbol used to separate the integer portion of a number from the fractional portion. In American English, this character is a period; in much of Europe, it is a comma. Conversely, the thousands separator that separates numbers larger than three digits is a comma in American English, and a period in much of Europe.</P>
<P>The convention for grouping digits also varies. In American English, digits are grouped by threes, but there are many other possibilities. In the example below, the same number is written as it would be locally in three different countries:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">1,000,000.55</P>
</td><td valign=top><P CLASS="TABLE">US</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">1.000.000,55</P>
</td><td valign=top><P CLASS="TABLE">Germany</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">10,00,000.55</P>
</td><td valign=top><P CLASS="TABLE">Nepal</P>
</td></tr>
</TABLE>
<A NAME="idx479"><!></A>
<A NAME="2323"><H3>23.2.3 Currency</H3></A>
<A NAME="idx480"><!></A>
<P>We are all aware that countries use different currencies. However, not everyone realizes the many different ways we can represent units of currency. For example, the symbol for a currency can vary. Here are two different ways of representing the same amount in US dollars:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">$24.99</P>
</td><td valign=top><P CLASS="TABLE">US</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">USD 24.99</P>
</td><td valign=top><P CLASS="TABLE">International currency symbol for the US</P>
</td></tr>
</TABLE>
<P>The placement of the currency symbol varies for different currencies, too, appearing before, after, or even within the numeric value:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">&#165; 155</P>
</td><td valign=top><P CLASS="TABLE">Japan</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">13,50 DM</P>
</td><td valign=top><P CLASS="TABLE">Germany</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>&#163;</SAMP>14 19s. 6d.</P>
</td><td valign=top><P CLASS="TABLE">England before decimalization</P>
</td></tr>
</TABLE>
<P>The format of negative currency values differs:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">&ouml;S 1,1</P>
</td><td valign=top><P CLASS="TABLE">-&ouml;S 1,1</P>
</td><td valign=top><P CLASS="TABLE">Austria</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">1,1 DM</P>
</td><td valign=top><P CLASS="TABLE">-1,1 DM</P>
</td><td valign=top><P CLASS="TABLE">Germany</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">SFr. 1.1</P>
</td><td valign=top><P CLASS="TABLE">SFr.-1.1</P>
</td><td valign=top><P CLASS="TABLE">Switzerland</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">HK$1.1</P>
</td><td valign=top><P CLASS="TABLE">(HK$1.1)</P>
</td><td valign=top><P CLASS="TABLE">Hong Kong</P>
</td></tr>
</TABLE>
<A NAME="idx481"><!></A>
<A NAME="2324"><H3>23.2.4 Time and Date</H3></A>
<A NAME="idx482"><!></A>
<P>Local conventions also determine how<I> time </I>and<I> date </I>are displayed. Some countries use a 24-hour clock; others use a 12-hour clock. Names and abbreviations for days of the week and months of the year vary by language.</P>
<P>Customs dictate the ordering of the year, month, and day, as well as the separating delimiters for their numeric representation. To designate years, some regions use seasonal, astronomical, or historical criteria, instead of the Western Gregorian calendar system. For example, the official Japanese calendar is based on the year of reign of the current Emperor.</P>
<P>The following example shows short and long representations of the same date in different countries: </P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">10/29/96</P>
</td><td valign=top><P CLASS="TABLE">Tuesday, October 29, 1996</P>
</td><td valign=top><P CLASS="TABLE">US</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">1996. 10. 29.</P>
</td><td valign=top><P CLASS="TABLE">1996. okt&oacute;ber 29.</P>
</td><td valign=top><P CLASS="TABLE">Hungary</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">29/10/96</P>
</td><td valign=top><P CLASS="TABLE">marted&igrave; 29 ottobre 1996</P>
</td><td valign=top><P CLASS="TABLE">Italy</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">29/10/1996</P>
</td><td valign=top><P CLASS="TABLE"><IMG SRC="images/captau.gif"><IMG SRC="images/rho.gif"><IMG SRC="images/iota.gif"><IMG SRC="images/tau.gif"><IMG SRC="images/eta.gif">, 29 <IMG SRC="images/capomicr.gif"><IMG SRC="images/kappa.gif"><IMG SRC="images/tau.gif"><IMG SRC="images/omega.gif"><IMG SRC="images/beta.gif"><IMG SRC="images/rho.gif"><IMG SRC="images/iota.gif"><IMG SRC="images/omicron.gif"><IMG SRC="images/upsilon.gif"> 1996</P>
</td><td valign=top><P CLASS="TABLE">Greece</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">29.10.96</P>
</td><td valign=top><P CLASS="TABLE">Dienstag, 29. Oktober 1996</P>
</td><td valign=top><P CLASS="TABLE">Germany</P>
</td></tr>
</TABLE>
<P>The following example shows different representations of the same time:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">4:55 pm</P>
</td><td valign=top><P CLASS="TABLE">US time</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">16:55 Uhr</P>
</td><td valign=top><P CLASS="TABLE">German time</P>
</td></tr>
</TABLE>
<P>And the following example shows different representations of the same time:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">11:45:15</P>
</td><td valign=top><P CLASS="TABLE">Digital representation, US</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">11:45:15 &#181;&#181;</P>
</td><td valign=top><P CLASS="TABLE">Digital representation, Greece</P>
</td></tr>
</TABLE>
<A NAME="idx483"><!></A>
<A NAME="2325"><H3>23.2.5 Ordering</H3></A>
<A NAME="idx484"><!></A>
<P>Languages may vary regarding <I>collating sequence</I>; that is, their rules for ordering or sorting characters or strings. The following example compares the same list of words ordered alphabetically by different collating sequences:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE"><B><I>Sorted by ASCII rules:</I></B></P>
</td><td valign=top><P CLASS="TABLE"><B><I>Sorted by German rules:</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">Airplane</P>
</td><td valign=top><P CLASS="TABLE">Airplane</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">Zebra</P>
</td><td valign=top><P CLASS="TABLE">&auml;hnlich</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">bird</P>
</td><td valign=top><P CLASS="TABLE">bird</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">car</P>
</td><td valign=top><P CLASS="TABLE">car</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">&auml;hnlich</P>
</td><td valign=top><P CLASS="TABLE">Zebra</P>
</td></tr>
</TABLE>
<P>The ASCII collation orders elements according to the numeric value of bytes, which does not meet the requirements of English language dictionary sorting. This is because lexicographical order sorts <SAMP>a</SAMP> after <SAMP>A</SAMP> and before <SAMP>B</SAMP>, whereas ASCII-based order sorts <SAMP>a</SAMP> after the entire set of uppercase letters.</P>
<P>The German alphabet sorts <SAMP>&auml;</SAMP> before <SAMP><B>b</B></SAMP>, whereas the ASCII order sorts an umlaut after all other letters.</P>
<P>In addition to specifying the ordering of individual characters, some languages specify that certain groups of characters should be clustered and treated as a single character. The following example shows the difference this can make in an ordering:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE"><B><I>Sorted by ASCII rules:</I></B></P>
</td><td valign=top><P CLASS="TABLE"><B><I>Sorted by Spanish rules:</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">chaleco</P>
</td><td valign=top><P CLASS="TABLE">cuna</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">cuna</P>
</td><td valign=top><P CLASS="TABLE">chaleco</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">d&iacute;a</P>
</td><td valign=top><P CLASS="TABLE">d&iacute;a</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">llava</P>
</td><td valign=top><P CLASS="TABLE">loro</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">loro</P>
</td><td valign=top><P CLASS="TABLE">llava</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">ma&iacute;z</P>
</td><td valign=top><P CLASS="TABLE">ma&iacute;z</P>
</td></tr>
</TABLE>
<P>The word <SAMP>llava</SAMP> is sorted after <SAMP>loro</SAMP> and before <SAMP>ma&iacute;z</SAMP>, because in Spanish <SAMP>ll</SAMP> is a digraph, i.e., it is treated as a single character that is sorted after <SAMP>l</SAMP> and before <SAMP>m</SAMP>. Similarly, the digraph <SAMP>ch</SAMP> in Spanish is treated as a single character to be sorted after <SAMP>c</SAMP>, but before <SAMP>d</SAMP>. Two characters that are paired and treated as a single character are referred to as a <I>two-to-one</I> <I>character code pair</I>.</P>
<P>In other cases, one character is treated as if it were actually two characters. The German single character <SAMP>&#223;</SAMP>, called the <I>sharp s</I>, is treated as <SAMP>ss</SAMP>. This treatment makes a difference in the ordering, as shown in the example below:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE"><B><I>Sorted by ASCII rules:</I></B></P>
</td><td valign=top><P CLASS="TABLE"><B><I>Sorted by German rules:</I></B></P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">Rosselenker</P>
</td><td valign=top><P CLASS="TABLE">Rosselenker</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">Rostbratwurst</P>
</td><td valign=top><P CLASS="TABLE">Ro&#223;haar</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">Ro&#223;haar</P>
</td><td valign=top><P CLASS="TABLE">Rostbratwurst</P>
</td></tr>
</TABLE>
<BR>
<HR>
<A HREF="23-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="23-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,161 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Character Encodings for Localizing Alphabets</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="23-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="23-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>23.3 Character Encodings for Localizing Alphabets</H2>
<A NAME="idx485"><!></A>
<P>We know that different languages can have different alphabets. The first step in localizing an alphabet is to find a way to represent, or <I>encode</I>, all its characters. In general, alphabets may have different <I>character encodings</I>.</P>
<A NAME="idx486"><!></A>
<P>The <I>7-bit ASCII codeset </I>is the traditional code on UNIX systems.</P>
<A NAME="idx487"><!></A>
<P>The<I> 8-bit codesets </I>permit the processing of many Eastern and Western European, Middle Eastern, and Asian Languages. Some are strictly extensions of the 7-bit ASCII codeset; these include the 7-bit ASCII codes and additionally support 128-character codes beyond those of ASCII. Such extensions meet the needs of Western European users. To support languages that have completely different alphabets, such as Arabic and Greek, larger 8-bit codesets have been designed.</P>
<A NAME="idx488"><!></A>
<P><I>Multibyte character codes </I>are required for alphabets of more than 256 characters, such as kanji, which consists of Japanese ideographs based on Chinese characters. Kanji has tens of thousands of characters, each of which is represented by two bytes. To ensure backward compatibility with ASCII, a multibyte codeset is a superset of the ASCII codeset and consists of a mixture of one- and two-byte characters.</P>
<P>For such languages, several encoding schemes have been defined. These encoding schemes provide a set of rules for parsing a byte stream into a group of coded characters.</P>
<A NAME="2331"><H3>23.3.1 Multibyte Encodings</H3></A>
<A NAME="idx489"><!></A>
<P>Handling multibyte character encodings is a challenging task. It involves parsing multibyte character sequences, and in many cases requires conversions between multibyte characters and wide characters.</P>
<P>Understanding multibyte encoding schemes is easier when explained by means of a typical example. One of the earliest and probably biggest markets for multibyte character support is in Japan. Therefore, the following examples are based on encoding schemes for Japanese text processing.</P>
<A NAME="idx490"><!></A>
<P>In Japan, a single text message can be composed of characters from four different writing systems. <I>Kanji</I> has tens of thousands of characters, which are represented by pictures. <I>Hiragana</I> and <I>katakana</I> are syllabaries, each containing about 80 sounds, which are also represented as ideographs. The <I>Roman</I> characters include some 95 letters, digits, and punctuation marks. </P>
<A NAME="idx491"><!></A>
<P><A HREF="23-3.html#Figure&nbsp;1">Figure&nbsp;1</A> gives an example of an encoded Japanese sentence composed of these four writing systems:</P>
<A NAME="idx492"><!></A>
<H4><A NAME="Figure&nbsp;1">Figure&nbsp;1: A Japanese sentence mixing four writing systems</A></H4>
<P><IMG SRC="images/locfig1.gif" WIDTH=688 HEIGHT=166></P>
<P>The sentence means: "Encoding methods such as JIS can support texts that mix Japanese and English."</P>
<P>A number of Japanese character sets are common:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">JIS C 6226-1978</P>
</td><td valign=top><P CLASS="TABLE">JIS X 0208-1983</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">JIS X 0208-1990</P>
</td><td valign=top><P CLASS="TABLE">JIS X 0212-1990</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">JIS-ROMAN</P>
</td><td valign=top><P CLASS="TABLE">ASCII</P>
</td></tr>
</TABLE>
<P>There is no universally recognized multibyte encoding scheme for Japanese. Instead, we deal with the three common multibyte encoding schemes defined below:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">JIS (Japanese Industrial Standard)</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">Shift-JIS</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">EUC (Extended UNIX Code)</P>
</td></tr>
</TABLE>
<A NAME="idx493"><!></A>
<A NAME="2331-1"><H4>23.3.1.1 JIS Encoding</H4></A>
<A NAME="idx494"><!></A>
<P>The <I>JIS</I><B>, </B>or<B> </B><I>Japanese Industrial Standard</I><B>, </B>supports a number of standard Japanese character sets, some requiring one byte, others two. Escape sequences are required to shift between one- and two-byte modes.</P>
<A NAME="idx495"><!></A>
<P><I>Escape sequences</I>, also referred to as<I> shift sequences</I>, are sequences of <I>control</I> <I>characters</I>. Control characters do not belong to any of the alphabets. They are artificial characters that do not have a visual representation. However, they are part of the encoding scheme, where they serve as separators between different character sets, and indicate a switch in the way a character sequence is interpreted. The use of the shift sequence is demonstrated in <A HREF="23-3.html#Figure&nbsp;2">Figure&nbsp;2</A>.</P>
<A NAME="idx496"><!></A>
<H4><A NAME="Figure&nbsp;2">Figure&nbsp;2: An example of a Japanese text encoded in JIS</A></H4>
<P><IMG SRC="images/locfig2.gif" WIDTH=719 HEIGHT=221></P>
<A NAME="idx497"><!></A>
<P>For encoding schemes containing shift sequences, like JIS, it is necessary to maintain a <I>shift state </I>while parsing a character sequence. In the example above, we are in some initial shift state at the start of the sequence. Here it is ASCII. Therefore, characters are assumed to be one-byte ASCII codes until the shift sequence <SAMP>&lt;ESC&gt;$B</SAMP> is seen. This switches us to two-byte mode, as defined by JIS X 0208-1983. The shift sequence <SAMP>&lt;ESC&gt;(B</SAMP> then switches us back to ASCII mode.</P>
<P>Encoding schemes that use shift state are not very efficient for internal storage or processing. Sometimes shift sequences require up to six bytes. Frequent switching between character sets in a file of strings could cause the number of bytes used in shift sequences to exceed the number of bytes used to represent the actual data!</P>
<P>Encodings containing shift sequences are used primarily as an external code, which allows information interchange between a program and the outside world.</P>
<A NAME="idx498"><!></A>
<A NAME="2331-2"><H4>23.3.1.2 Shift-JIS Encoding</H4></A>
<P>Despite its name, Shift-JIS has nothing to do with shift sequences and states. In this encoding scheme, each byte is inspected to see if it is a one-byte character or the first byte of a two-byte character. This is determined by reserving a set of byte values for certain purposes. For example:</P>
<UL>
<LI><P CLASS="LIST">Any byte having a value in the range 0x21-7E is assumed to be a one-byte ASCII/JIS Roman character.</P></LI>
<LI><P CLASS="LIST">Any byte having a value in the range 0xA1-DF is assumed to be a one-byte half-width katakana character.</P></LI>
<LI><P CLASS="LIST">Any byte having a value in the range 0x81-9F or 0xE0-EF is assumed to be the first byte of a two-byte character from the set JIS X 0208-1990. The second byte must have a value in the range 0x40-7E or 0x80-FC.</P></LI>
</UL>
<P>While this encoding is more compact than JIS, it cannot represent as many characters as JIS. In fact, Shift-JIS cannot represent any characters in the supplemental character set JIS X 0212-1990, which contains more than 6,000 characters.</P>
<A NAME="idx499"><!></A>
<A NAME="2331-3"><H4>23.3.1.3 EUC Encoding</H4></A>
<A NAME="idx500"><!></A>
<P>Extended UNIX Code (EUC) is not peculiar to Japanese encoding. It was developed as a method for handling multiple character sets, Japanese or otherwise, within a single text stream.</P>
<P>The EUC encoding is much more extensible than Shift-JIS since it allows for characters containing more than two bytes. The encoding scheme used for Japanese characters is as follows:</P>
<UL>
<LI><P CLASS="LIST">Any byte having a value in the range 0x21-7E is assumed to be a one-byte ASCII/JIS Roman character.</P></LI>
<LI><P CLASS="LIST">Any byte having a value in the range 0xA1-FE is assumed to be the first byte of a two-byte character from the set JIS X0208-1990. The second byte must also have a value in that range.</P></LI>
<LI><P CLASS="LIST">Any byte having the value 0x8E is assumed to be followed by a second byte with a value in the range 0xA1-DF, which represents a half-width katakana character.</P></LI>
<LI><P CLASS="LIST">Any byte having the value 0x8F is assumed to be followed by two more bytes with values in the range 0xA1-FE, which together represent a character from the set JIS X0212-1990.</P></LI>
</UL>
<P>The last two cases involve a prefix byte with values 0x8E and 0x8F, respectively. These bytes are somewhat like shift sequences in that they introduce a change in subsequent byte interpretation. However, unlike the shift sequences in JIS which introduce a sequence, these prefix bytes must precede <I>every</I> multibyte character, not just the first in a sequence. For this reason, each multibyte character encoded in this manner stands alone and EUC is not considered to involve shift states.</P>
<A NAME="2331-4"><H4>23.3.1.4 Uses of the Three Multibyte Encodings</H4></A>
<A NAME="idx501"><!></A>
<P>The three multibyte encodings just described are typically used in separate areas:</P>
<UL>
<LI><P CLASS="LIST">JIS is the primary encoding method used for electronic transmission such as email because it uses only 7 bits of each byte. This is required because some network paths strip the eighth bit from characters. Escape sequences are used to switch between one- and two-byte modes, as well as between different character sets.</P></LI>
<LI><P CLASS="LIST">Shift-JIS was invented by Microsoft and is used on MS-DOS-based machines. Each byte is inspected to see if it is a one-byte character or the first byte of a two-byte character. Shift-JIS does not support as many characters as JIS and EUC do.</P></LI>
<LI><P CLASS="LIST">EUC encoding is implemented as the internal code for most UNIX-based platforms. It allows for characters containing more than two bytes, and is much more extensible that Shift-JIS. EUC is a general method for handling multiple character sets. It is not peculiar to Japanese encoding.</P></LI>
</UL>
<A NAME="2332"><H3>23.3.2 Wide Characters</H3></A>
<A NAME="idx502"><!></A>
<P>Multibyte encoding provides an efficient way to move characters around outside programs, and between programs and the outside world. Once inside a program, however, it is easier and more efficient to deal with characters that have the same size and format. We call these <I>wide</I> <I>characters</I>.</P>
<P>Here is an example that illustrates how wide characters make text processing inside a program easier. Consider a filename string containing a directory path with adjacent names separated by a slash, such as <SAMP>/CC/include/locale.h</SAMP>. To find the actual filename in a single-byte character string, we can start at the back of the string. When we find the first separator, we know where the filename starts. If the string contains multibyte characters, we scan from the front so we don't inspect bytes out of context. If the string contains wide characters, however, we can treat it like a single-byte character and scan from the back.</P>
<P>Conceptually, you can think of wide character sets as being extended ASCII or EBCDIC; each unique character is assigned a distinct value. Since they are used as the counterpart to a multibyte encoding, wide character sets must allow representation of all characters that can be represented in a multibyte encoding as wide characters. As multibyte encodings support thousands of characters, wide characters are usually larger that one byte -- typically two or four bytes. All characters in a wide character set are of equal size. The size of a wide character is not universally fixed, although this depends on the particular wide character set.</P>
<P>There are many wide character standards, including those shown below:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">ISO 10646.UCS-2</P>
</td><td valign=top><P CLASS="TABLE">16-bit characters</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">ISO 10646.UCS-4</P>
</td><td valign=top><P CLASS="TABLE">32-bit characters</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">Unicode</P>
</td><td valign=top><P CLASS="TABLE">16-bit characters</P>
</td></tr>
</TABLE>
<P>The programming language C++ supports wide characters; their native type in C++ is called <SAMP>wchar_t</SAMP>. The syntax for wide character constants and wide character strings is similar to that for ordinary, narrow character constants and strings:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE"><SAMP>L'a'</SAMP> is a wide character constant, and</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>L"abc"</SAMP> is a wide character string.</P>
</td></tr>
</TABLE>
<A NAME="idx503"><!></A>
<A NAME="2333"><H3>23.3.3 Conversion between Multibyte and Wide Characters</H3></A>
<P>Since wide characters are usually used for internal representation of characters in a program, and multibyte encodings are used for external representation, converting multibytes to wide characters is a common task during input/output operations. Input to and output from a file is a typical example. The file usually contains multibyte characters. When you read such a file, you convert these multibyte characters into wide characters that you store in an internal wide character buffer for further processing. When you write to a multibyte file, you have to convert the wide characters held internally into multibytes for storage on a external file. <A HREF="23-3.html#Figure&nbsp;3">Figure&nbsp;3</A> demonstrates how this conversion during file input is done:</P>
<A NAME="idx504"><!></A>
<H4><A NAME="Figure&nbsp;3">Figure&nbsp;3: Conversion from a multibyte to a wide character encoding</A></H4>
<P><IMG SRC="images/locfig3.gif" WIDTH=502 HEIGHT=277></P>
<P>The conversion from a multibyte sequence into a wide character sequence requires expansion of one-byte characters into two- or four-byte wide characters. Escape sequences are eliminated. Multibytes that consist of two or more bytes are translated into their wide character equivalents.</P>
<BR>
<HR>
<A HREF="23-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="23-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,51 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Summary</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="23-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>23.4 Summary</H2>
<A NAME="idx505"><!></A>
<P>In this section, we discussed a variety of issues involved in developing software for worldwide use. For all of these areas in which cultural conventions differ from one region to another, the <B></B>C++ Standard Library<B> </B>provides services that enable you to easily internationalize your C++ programs. These services include:</P>
<UL>
<LI><P CLASS="LIST">Formatting and parsing of numbers, currency units, dates, and times</P></LI>
<LI><P CLASS="LIST">Handling different alphabets, their character classification, and collation sequences</P></LI>
<LI><P CLASS="LIST">Converting codesets, including multibyte to wide character conversion</P></LI>
<LI><P CLASS="LIST">Handling messages in different languages. </P></LI>
</UL>
<BR>
<HR>
<A HREF="23-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,62 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Internationalization and Localization</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="VII.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="23-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 23: Internationalization and Localization</H1>
<UL>
<UL><LI><A HREF="23-1.html">23.1 Defining the Terms</A></LI></UL>
<UL><LI><A HREF="23-2.html">23.2 Localizing Cultural Conventions</A></LI></UL>
<UL><UL><LI><A HREF="23-2.html#2321">23.2.1 Language</A></LI></UL></UL>
<UL><UL><LI><A HREF="23-2.html#2322">23.2.2 Numbers</A></LI></UL></UL>
<UL><UL><LI><A HREF="23-2.html#2323">23.2.3 Currency</A></LI></UL></UL>
<UL><UL><LI><A HREF="23-2.html#2324">23.2.4 Time and Date</A></LI></UL></UL>
<UL><UL><LI><A HREF="23-2.html#2325">23.2.5 Ordering</A></LI></UL></UL>
<UL><LI><A HREF="23-3.html">23.3 Character Encodings for Localizing Alphabets</A></LI></UL>
<UL><UL><LI><A HREF="23-3.html#2331">23.3.1 Multibyte Encodings</A></LI></UL></UL>
<UL><UL><UL><LI><A HREF="23-3.html#2331-1">23.3.1.1 JIS Encoding</A></LI></UL></UL></UL>
<UL><UL><UL><LI><A HREF="23-3.html#2331-2">23.3.1.2 Shift-JIS Encoding</A></LI></UL></UL></UL>
<UL><UL><UL><LI><A HREF="23-3.html#2331-3">23.3.1.3 EUC Encoding</A></LI></UL></UL></UL>
<UL><UL><UL><LI><A HREF="23-3.html#2331-4">23.3.1.4 Uses of the Three Multibyte Encodings</A></LI></UL></UL></UL>
<UL><UL><LI><A HREF="23-3.html#2332">23.3.2 Wide Characters</A></LI></UL></UL>
<UL><UL><LI><A HREF="23-3.html#2333">23.3.3 Conversion between Multibyte and Wide Characters</A></LI></UL></UL>
<UL><LI><A HREF="23-4.html">23.4 Summary</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="VII.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="23-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,112 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The C Locale</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="24.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>24.1 The C Locale</H2>
<A NAME="idx506"><!></A>
<P>All the culture and language dependencies discussed in the previous section need to be represented in an operating system. This information is usually represented in a kind of language table, called a <I>locale</I>.</P>
<A NAME="idx507"><!></A>
<P>The X/Open consortium has standardized a variety of services for Native Language Support (NLS<I>)</I> in the programming language C. This standard is commonly known as XPG4. Internationalization services as well as localization support are included in X/Open's <I>Native Language Support</I>. The description below is based on this standard.</P>
<A NAME="idx508"><!></A>
<P>According to XPG4, the C locale is composed of several <I>categories</I>, which are given in <A HREF="24-1.html#Table&nbsp;24">Table&nbsp;24</A>.</P>
<A NAME="idx509"><!></A>
<H4><A NAME="Table&nbsp;24">Table&nbsp;24: Categories of the C locale&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>Category</B>
</td><td valign=top><B>Content</B>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>LC_NUMERIC</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Rules and symbols for numbers</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>LC_TIME</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Values for date and time information</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>LC_MONETARY</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Rules and symbols for monetary information</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>LC_CTYPE</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Character classification and case conversion</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>LC_COLLATE</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Collation sequence</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>LC_MESSAGES</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Formats and values of messages</P>
</td></tr>
</TABLE>
<A NAME="idx510"><!></A>
<P>The external representation of a C locale is usually a <I>file</I> in UNIX. Other operating systems may use other representations. The external representation is transformed into an internal memory representation by calling the function <SAMP>setlocale()</SAMP>, as shown in <A HREF="24-1.html#Figure&nbsp;4">Figure&nbsp;4</A>:</P>
<H4><A NAME="Figure&nbsp;4">Figure&nbsp;4: Transformation of a C locale from external to internal representation</A></H4>
<P><IMG SRC="images/locfig4.gif" WIDTH=583 HEIGHT=302></P>
<P>Inside a program, the C locale is represented by one or more global data structures. The C library provides a set of functions that use information from those global data structures to adapt their behavior to local conventions. Examples of these functions and the information they cover are listed in <A HREF="24-1.html#Table&nbsp;25">Table&nbsp;25</A>:</P>
<A NAME="idx511"><!></A>
<H4><A NAME="Table&nbsp;25">Table&nbsp;25: C locale functions and the information they cover&nbsp;</A></H4>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><B>C Locale Function</B>
</td><td valign=top><B>Information Covered</B>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>setlocale()</SAMP>, ...</P>
</td><td valign=top><P CLASS="TABLE">Locale initialization and </P>
<P CLASS="TABLE">language information</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>isalpha()</SAMP>, <SAMP>isupper()</SAMP>, <SAMP>isdigit()</SAMP>, ...</P>
</td><td valign=top><P CLASS="TABLE">Character classification</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>strftime()</SAMP>, ...</P>
</td><td valign=top><P CLASS="TABLE">Date and time functions</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>strfmon()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Monetary functions</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>printf(), scanf()</SAMP>, ...</P>
</td><td valign=top><P CLASS="TABLE">Number parsing and formatting</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>strcoll()</SAMP>, <SAMP>wcscoll()</SAMP>, ...</P>
</td><td valign=top><P CLASS="TABLE">String collation</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>mblen()</SAMP>, <SAMP>mbtowc()</SAMP>, <SAMP>wctomb()</SAMP>, ...</P>
</td><td valign=top><P CLASS="TABLE">Multibyte functions</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE"><SAMP>catopen()</SAMP>, <SAMP>catgets()</SAMP>, <SAMP>catclose()</SAMP></P>
</td><td valign=top><P CLASS="TABLE">Message retrieval</P>
</td></tr>
</TABLE>
<BR>
<HR>
<A HREF="24.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,81 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The C++ Locales</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="24-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>24.2 The C++ Locales</H2>
<P>In C++, a locale is a class called <B><I><A HREF="../stdlibref/locale.html">locale</A></I></B> provided by the C++ Standard Library. The C++ class <B><I>locale</I></B> differs from the C locale because it is more than a language table, or data representation of the various culture and language dependencies. It also includes the internationalization services, which in C are global functions.</P>
<A NAME="idx512"><!></A>
<P>In C++, internationalization semantics are broken out into separate classes called <I>facets</I>. Each facet handles a set of internationalization services; for example, the formatting of monetary values. Facets may also represent a set of culture and language dependencies, such as the rules and symbols for monetary information.</P>
<A NAME="idx513"><!></A>
<P>Each locale object maintains a set of facet objects. In fact, you can think of a C++ locale as a container of facets, as illustrated in <A HREF="24-2.html#Figure&nbsp;5">Figure&nbsp;5</A> below:</P>
<A NAME="idx514"><!></A>
<H4><A NAME="Figure&nbsp;5">Figure&nbsp;5: A C++ locale is a container of facets</A></H4>
<P><IMG SRC="images/locfig5.gif" WIDTH=551 HEIGHT=409></P>
<A NAME="2421"><H3>24.2.1 Facets</H3></A>
<A NAME="idx515"><!></A>
<P>Facet classes encapsulate data that represents a set of culture and language dependencies, and offer a set of related internationalization services. Facet classes are very flexible. They can contain just about any internationalization service you can invent. The C++ Standard Library offers a number of predefined standard facets, which provide services similar to those contained in the C library. However, you could bundle additional internationalization services into a new facet class, or purchase a facet library.</P>
<A NAME="2421-1"><H4>24.2.1.1 The Standard Facets</H4></A>
<A NAME="idx516"><!></A>
<P>The C locale is composed of six categories of locale-dependent information: <SAMP>LC_NUMERIC</SAMP> (rules and symbols for numbers), <SAMP>LC_TIME</SAMP> (values for date and time information), <SAMP>LC_MONETARY</SAMP> (rules and symbols for monetary information), <SAMP>LC_CTYPE</SAMP> (character classification and conversion), <SAMP>LC_COLLATE</SAMP> (collation sequence), and <SAMP>LC_MESSAGES</SAMP> (formats and values of messages). </P>
<A NAME="idx517"><!></A>
<P>Similarly, there are six categories of standard facet classes. A detailed description of these facets is contained in the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A>, but a brief overview is given below. Note that an abbreviation like <B><I><A HREF="../stdlibref/num-get.html">num_get&lt;&gt;</A></I></B> means that <B><I>num_get</I></B> is a class template taking two template arguments, a character type, and an input iterator type. The categories of the standard facets are:</P>
<UL>
<A NAME="idx518"><!></A>
<LI><P CLASS="LIST"><B>Numeric. </B>The facet classes <B><I><A HREF="../stdlibref/num-get.html">num_get&lt;&gt;</A></I></B> and <B><I><A HREF="../stdlibref/num-put.html">num_put&lt;&gt;</A></I></B> handle numeric formatting and parsing. The facet classes provide <SAMP>get()</SAMP> and <SAMP>put()</SAMP> member functions for values of type <SAMP>long</SAMP>, <SAMP>double</SAMP>, etc.</P></LI>
<A NAME="idx519"><!></A>
<P CLASS="LIST">The facet class <B><I><A HREF="../stdlibref/numpunct.html">numpunct&lt;&gt;</A></I></B> specifies numeric punctuation. It provides functions like <SAMP>decimal_point()</SAMP>, <SAMP>thousands_sep()</SAMP>, etc.</P>
<A NAME="idx520"><!></A>
<LI><P CLASS="LIST"><B>Time. </B>The facet classes <B><I><A HREF="../stdlibref/time-get.html">time_get&lt;&gt;</A></I></B> and <B><I><A HREF="../stdlibref/time-put.html">time_put&lt;&gt;</A></I></B> handle date and time formatting and parsing. They provide functions like <SAMP>get_time()</SAMP>, <SAMP>get_date()</SAMP>, <SAMP>get_weekday()</SAMP>, etc.</P></LI>
<A NAME="idx521"><!></A>
<LI><P CLASS="LIST"><B>Monetary. </B>The facet classes <B><I><A HREF="../stdlibref/money-get.html">money_get&lt;&gt;</A></I></B> and <B><I><A HREF="../stdlibref/money-put.html">money_put&lt;&gt;</A></I></B> handle formatting and parsing of monetary values. They provide <SAMP>get()</SAMP> and <SAMP>put()</SAMP> member functions that parse or produce a sequence of digits, representing a count of the smallest unit of the currency. For example, the sequence $1,056.23 in a common US locale would yield 105623 units, or the character sequence "105623".</P></LI>
<A NAME="idx522"><!></A>
<P CLASS="LIST">The facet class <B><I><A HREF="../stdlibref/moneypunct.html">moneypunct&lt;&gt;</A></I></B> handles monetary punctuation like the facet <B><I><A HREF="../stdlibref/numpunct.html">numpunct&lt;&gt;</A></I></B> handles numeric punctuation. It comes with functions like <SAMP>curr_symbol()</SAMP>, etc.</P>
<A NAME="idx523"><!></A>
<LI><P CLASS="LIST"><B>Ctype. </B>The facet class <B><I><A HREF="../stdlibref/ctype.html">ctype&lt;&gt;</A></I></B> encapsulates the C++ Standard Library <B><I>ctype</I></B> features for character classification, like <SAMP>tolower()</SAMP>, <SAMP>toupper()</SAMP>, <SAMP>isspace()</SAMP>, <SAMP>isprint()</SAMP>, etc.</P></LI>
<A NAME="idx524"><!></A>
<P CLASS="LIST">The facet class <B><I><A HREF="../stdlibref/codecvt.html">codecvt&lt;&gt;</A></I></B> is used when converting from one encoding scheme to another, such as from the multibyte encoding JIS to the wide-character encoding Unicode. The main member functions are <SAMP>in()</SAMP> and <SAMP>out()</SAMP>. There is a template specialization <B><I>codecvt&lt;&gt;</I></B> for multibyte to wide character conversions.</P>
<A NAME="idx525"><!></A>
<LI><P CLASS="LIST"><B>Collate. </B>The facet class <B><I><A HREF="../stdlibref/collate.html">collate&lt;&gt;</A></I></B> provides features for string collation, including a <SAMP>compare()</SAMP> function used for string comparison.</P></LI>
<A NAME="idx526"><!></A>
<LI><P CLASS="LIST"><B>Messages. </B>The facet class <B><I><A HREF="../stdlibref/messages.html">messages&lt;&gt;</A></I></B> implements the X/Open message retrieval facility. It provides facilities to access message catalogues via <SAMP>open()</SAMP> and <SAMP>close(catalog)</SAMP>, and to retrieve messages via <SAMP>get(..., int msgid,...)</SAMP>.</P></LI>
</UL>
<P>The names of the standard facets obey certain naming rules. The <SAMP>get</SAMP> facet classes, like <B><I><A HREF="../stdlibref/num-get.html">num_get</A></I></B> and <B><I><A HREF="../stdlibref/time-get.html">time_get</A></I></B>, handle parsing. The <SAMP>put</SAMP> facet classes handle formatting. The <SAMP>punct</SAMP> facet classes, like <B><I><A HREF="../stdlibref/numpunct.html">numpunct</A></I></B> and <B><I><A HREF="../stdlibref/moneypunct.html">moneypunct</A></I></B>, represent rules and symbols.</P>
<BR>
<HR>
<A HREF="24-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,158 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Differences between the C Locale and the C++ Locales</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="24-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>24.3 Differences between the C Locale and the C++ Locales</H2>
<A NAME="idx527"><!></A>
<P>As we have seen so far, the C locale and the C++ locale offer similar services. However, the semantics of the C++ locale are different from the semantics of the C locale:</P>
<UL>
<LI><P CLASS="LIST">The <I>Standard C locale </I>is a global resource: there is only one locale for the entire application. This makes it hard to build an application that has to handle several locales at a time.</P></LI>
<LI><P CLASS="LIST">The <I>Standard C++ locale</I> is a class. Numerous instances of the standard <B><I><A HREF="../stdlibref/locale.html">locale</A></I></B> class can be created at will, so you can have as many locale objects as you need. </P></LI>
</UL>
<P>To explore this difference in further detail, let us see how locales are typically used.</P>
<A NAME="2431"><H3>24.3.1 Common Uses of the C locale</H3></A>
<A NAME="idx528"><!></A>
<P>The C locale is commonly used as a default locale, a native locale, or in multiple locale applications.</P>
<A NAME="idx529"><!></A>
<P><B>Default locale. </B>As a developer, you may never require internationalization features, and thus you may never call <SAMP>std::setlocale()</SAMP>. If you can safely assume that users of your applications are accommodated by the classic US English ASCII behavior, you have no need for localization. Without even knowing it, you always use the default locale, which is the US English ASCII locale.</P>
<A NAME="idx530"><!></A>
<P><B>Native locale. </B>If you do plan on localizing your program, the appropriate strategy may be to retrieve the native locale once at the beginning of your program, and never, ever change this setting again. This way your application adapts itself to one particular locale, and uses this throughout its entire runtime. Users of such applications can explicitly set their favorite locale before starting the application. On UNIX systems, they do this by setting environment variables such as <SAMP>LANG</SAMP>; other operating systems may use other methods.</P>
<P>In your program, you can specify that you want to use the user's preferred native locale by calling <SAMP>std::setlocale("")</SAMP> at startup, passing an empty string as the locale name. The empty string tells <SAMP>setlocale</SAMP> to use the locale specified by the user in the environment.</P>
<A NAME="idx531"><!></A>
<P><B>Multiple locales. </B>It may well happen that you do have to work with multiple locales. For example, to implement an application for Switzerland, you might want to output messages in Italian, French, and German. As the C locale is a global data structure, you must switch locales several times.</P>
<P>Let's look at an example of an application that works with multiple locales. Imagine an application that prints invoices to be sent to customers all over the world. Of course, the invoices must be printed in the customer's native language, so the application must write output in multiple languages. Prices to be included in the invoice are taken from a single price list. If we assume that the application is used by a US company, the price list is in US English.</P>
<P>The application reads input (the product price list) in US English, and writes output (the invoice) in the customer's native language, say German. Since there is only one global locale in C that affects both input and output, the global locale must change between input and output operations. Before a price is read from the English price list, the locale must be switched from the German locale used for printing the invoice to a US English locale. Before inserting the price into the invoice, the global locale must be switched back to the German locale. To read the next input from the price list, the locale must be switched back to English, and so forth. <A HREF="24-3.html#Figure&nbsp;6">Figure&nbsp;6</A> summarizes this activity.</P>
<A NAME="idx532"><!></A>
<H4><A NAME="Figure&nbsp;6">Figure&nbsp;6: Multiple locales in C</A></H4>
<P><IMG SRC="images/locfig6.gif" WIDTH=526 HEIGHT=270></P>
<A NAME="idx533"><!></A>
<P>Here is the C code that corresponds to the previous example:</P>
<UL><PRE>
double price;
char buf[SZ];
while ( ... ) // processing the German invoice
{
std::setlocale(LC_ALL, "En_US");
std::fscanf(priceFile,"%lf",&amp;price);
// convert $ to DM according to the current exchange rate
std::setlocale(LC_ALL,"De_DE");
std::strfmon(buf,SZ,"%n",price);
std::fprintf(invoiceFile,"%s",buf);
}
</PRE></UL>
<A NAME="idx534"><!></A>
<P>Using C++ locale objects dramatically simplifies the task of communicating between multiple locales. The iostreams in the C++ Standard Library are internationalized so that streams can be imbued with separate locale objects. For example, the input stream can be imbued with an English locale object, and the output stream can be imbued with a German locale object. In this way, switching locales becomes unnecessary, as demonstrated in <A HREF="24-3.html#Figure&nbsp;7">Figure&nbsp;7</A>:</P>
<A NAME="idx535"><!></A>
<H4><A NAME="Figure&nbsp;7">Figure&nbsp;7: Multiple locales in C++</A></H4>
<P><IMG SRC="images/locfig7.gif" WIDTH=618 HEIGHT=377></P>
<A NAME="idx536"><!></A>
<P>Here is the C++ code corresponding to the previous example:</P>
<UL><PRE>
priceFile.imbue(std::locale("En_US"));
invoiceFile.imbue(std::locale("De_DE"));
moneytype price;
while ( ... ) // processing the German invoice
{
priceFile &gt;&gt; price;
// convert $ to DM according to the current exchange rate
invoiceFile &lt;&lt; price;
}
</PRE></UL>
<P>This example assumes that you have created a class, <B><I>moneytype</I></B>, to represent monetary values, and that you have written iostream insertion <SAMP>&lt;&lt;</SAMP> and extraction <SAMP>&gt;&gt;</SAMP> operators for the class. Further, it assumes that these operators format and parse values using the <SAMP>std::money_put</SAMP> and <SAMP>std::money_get</SAMP> facets of the locales imbued on the streams they are operating on. See <A HREF="26.html">Chapter&nbsp;26</A> for a complete example of this technique using phone numbers rather than monetary values. The <B><I>moneytype</I></B> class is not part of the C++ Standard Library.</P>
<P>Because the examples given above are brief, switching locales might look like a minor inconvenience. However, it is a major problem once code conversions are involved.</P>
<A NAME="idx537"><!></A>
<P>To underscore the point, let us revisit the JIS encoding scheme using the shift sequence described in <A HREF="23-3.html#Figure&nbsp;2">Figure&nbsp;2</A>, which is repeated for convenience here as <A HREF="24-3.html#Figure&nbsp;8">Figure&nbsp;8</A>. As you remember, you must maintain a <I>shift state</I> with these encodings while parsing a character sequence:</P>
<A NAME="idx538"><!></A>
<H4><A NAME="Figure&nbsp;8">Figure&nbsp;8: The Japanese text from <A HREF="23-3.html#Figure&nbsp;2">Figure&nbsp;2</A> encoded in JIS</A></H4>
<P><IMG SRC="images/locfig8.gif" WIDTH=702 HEIGHT=224></P>
<P>Suppose you are parsing input from a multibyte file which contains text that is encoded in JIS, as shown in <A HREF="24-3.html#Figure&nbsp;9">Figure&nbsp;9</A>. While you parse this file, you have to keep track of the current shift state so you know how to interpret the characters you read, and how to transform them into the appropriate internal wide character representation.</P>
<A NAME="idx539"><!></A>
<H4><A NAME="Figure&nbsp;9">Figure&nbsp;9: Parsing input from a multibyte file using the global C locale</A></H4>
<P><IMG SRC="images/locfig9.gif" WIDTH=742 HEIGHT=379></P>
<A NAME="idx540"><!></A>
<P>The global C locale can be switched during parsing; for example, from a locale object specifying the input to be in JIS encoding, to a locale object using EUC encoding instead. The current shift state becomes invalid each time the locale is switched, and you have to carefully maintain the shift state in an application that switches locales.</P>
<P>As long as the locale switches are intentional, this problem can presumably be solved. However, in multithreaded environments, the global C locale may impose a severe problem, as it can be switched inadvertently by another otherwise unrelated thread of execution. For this reason, internationalizing a C program for a multithreaded environment is difficult.</P>
<P>If you use C++ locales, on the other hand, the problem simply goes away. You can imbue each stream with a separate locale object, making inadvertent switches impossible. Let us now see how C++ locales are intended to be used.</P>
<A NAME="2432"><H3>24.3.2 Common Uses of C++ Locales</H3></A>
<A NAME="idx541"><!></A>
<P>The C++ locale is commonly used as a default locale, with multiple locales, and as a global locale.</P>
<A NAME="idx542"><!></A>
<P><B>Classic locale.</B> If you are not involved with internationalizing programs, you won't need C++ locales any more than you need C locales. If you can safely assume that users of your applications are accommodated by classic US English ASCII behavior, you do not require localization features. For you, the C++ Standard Library provides a predefined locale object, <SAMP>std::locale::classic()</SAMP>, that represents the US English ASCII locale. </P>
<A NAME="idx543"><!></A>
<P><B>Native locale.</B> We use the term <I>native locale</I> to describe the locale that has been chosen as the preferred locale by the user or system administrator. On UNIX systems, this is usually done by setting environment variables such as <SAMP>LANG</SAMP>. You can create a C++ locale object for the native locale by calling the constructor <SAMP>std::locale("")</SAMP>, that&nbsp;is, by requesting a named locale using an empty string as the name. The empty string tells the system to get the locale name from the environment, in the same way as the C library function <SAMP>std::setlocale("")</SAMP>.</P>
<A NAME="idx544"><!></A>
<P><B>Named locales</B>. As implied above, a locale can have a name. The name of the classic locale is <SAMP>"C"</SAMP>. Unfortunately, the names of other locales are very much platform dependent. Consult your system documentation to determine what locales are installed and how they are named on your system. If you attempt to create a locale using a name that is not valid for your system, the constructor throws a <SAMP>runtime_error</SAMP> exception.</P>
<A NAME="idx545"><!></A>
<P><B>Multiple locales.</B> Working with many different locales becomes easy when you use C++ locales. Switching locales, as you did in C, is no longer necessary in C++. You can imbue each stream with a different locale object. You can pass locale objects around and use them in multiple places.</P>
<A NAME="idx546"><!></A>
<P><B>Global locale.</B> There is a global locale in C++, as there is in C. Initially, the global locale is the classic locale described above. You can change the global locale by calling <SAMP>std::locale::global()</SAMP>. </P>
<A NAME="idx547"><!></A>
<P>You can create snapshots of the current global locale by calling the default constructor for a locale, <SAMP>std::locale::locale()</SAMP>. Snapshots are immutable locale objects and are not affected by any subsequent changes to the global locale. </P>
<P>Internationalized components like iostreams use the global locale as a default. If you do not explicitly imbue a stream with a particular locale, it is imbued by default with a snapshot of whatever locale was global at the time the stream was created.</P>
<A NAME="idx548"><!></A>
<P>Using the global C++ locale, you can work much as you did in C. You activate the native locale once at program start -- in other words, you make it global -- and use snapshots of it thereafter for all tasks that are locale-dependent. The following code demonstrates this procedure:</P>
<UL><PRE>
std::locale::global(std::locale("")); //1
...
std::string t = print_date(today, std::locale()); //2
...
std::locale::global(std::locale("Fr_CH")); //3
...
std::cout &lt;&lt; something; //4
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>Make the native locale global.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>Use snapshots of the global locale whenever you need a locale object. Assume that <SAMP>print_date()</SAMP> is a function that formats dates. You would provide the function with a snapshot of the global locale in order to do the formatting.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>Switch the global locale; make a French locale global.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>Note that in this example, the standard stream <SAMP>cout</SAMP> is still imbued with the classic locale, because that was the global locale at program startup when <SAMP>std::cout</SAMP> was created. Changing the global locale does not change the locales of pre-existing streams. If you want to imbue the new global locale on <SAMP>cout</SAMP>, you should call <SAMP>std::cout.imbue(locale())</SAMP> after calling <SAMP>std::locale::global()</SAMP>.
</TABLE>
<A NAME="2433"><H3>24.3.3 The Relationship between the C Locale and the C++ Locale</H3></A>
<A NAME="idx549"><!></A>
<P>The C locale and the C++ locales are mostly independent. However, if a C++ locale object has a name, making it global via <SAMP>std::locale::global()</SAMP> causes the C locale to change through a call to <SAMP>std::setlocale()</SAMP>. When this happens, locale-sensitive C functions called from within a C++ program use the changed C locale.</P>
<P>There is no way to affect the C++ locale from within a C program.</P>
<BR>
<HR>
<A HREF="24-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,93 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The Locale Object</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="24-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>24.4 The Locale Object</H2>
<A NAME="idx550"><!></A>
<P>A C++ locale object is a container of facet objects which encapsulate internationalization services, and represent culture and language dependencies. Here are some functions of class <B><I><A HREF="../stdlibref/locale.html">locale</A></I></B> which allow you to create locales:</P>
<UL><PRE>
class locale {
public:
// construct/copy/destroy:
explicit locale(const char* std_name); //1
// global locale objects:
static const locale&amp; classic(); //2
};
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>You can create a locale object from a C locale's external representation. The constructor <SAMP>std::locale::locale(const char* std_name)</SAMP> takes the name of a C locale. This locale name is like the one you would use for a call to the C library function <SAMP>setlocale()</SAMP>.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>You can also use a predefined locale object, returned by <SAMP>std::locale::classic()</SAMP>, which represents the US English ASCII environment.
</TABLE>
<P>For a comprehensive description of the constructors described above, see the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A>.</P>
<A NAME="idx551"><!></A>
<P>It's important to understand that locales are immutable objects: once a locale object is created, it cannot be modified. This makes locales reliable and easy to use. As a programmer, you know that whenever you use pointers or references to elements held in a container, you have to worry about the validity of the pointers and references. If the container changes, pointers and references to its elements might not be valid any longer.</P>
<P>A locale object is a container, too. However, it is an immutable container; that is, it does not change. Therefore, you can take references to a locale's facet objects and pass the references around without worrying about their validity, as long as the locale object or any copy of it remains in existence. The locale object is never modified; no facets can be silently replaced.</P>
<P>At some time, you will most likely need locale objects other than the US classic locale or a snapshot of the global locale. Since locales are immutable objects, however, you cannot take one of these and replace its facet objects. You have to say at construction time how they shall be built.</P>
<A NAME="idx552"><!></A>
<P>Here are some constructors of class <B><I><A HREF="../stdlibref/locale.html">locale</A></I></B> which allow you to build a locale object by composition; in other words, you construct it by copying an existing locale object, and replacing one or several facet objects.</P>
<UL><PRE>
class locale {
public:
locale(const locale&amp; other, const char* std_name, category);
template &lt;class Facet&gt; locale(const locale&amp; other, Facet* f);
locale(const locale&amp; other, const locale&amp; one, category);
};
</PRE></UL>
<A NAME="idx553"><!></A>
<P>The following example shows how you can construct a locale object as a copy of the classic locale object, and take the numeric facet objects from a German locale object:</P>
<UL><PRE>
std::locale loc(std::locale::classic(),
std::locale("De_DE"), LC_NUMERIC);
</PRE></UL>
<P>For a comprehensive description of the constructors described above, see the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A>.</P>
<A NAME="idx554"><!></A>
<P>Copying a locale object is a cheap operation. You should have no hesitation about passing locale objects around by value. You may copy locale objects for composing new locale objects; you may pass copies of locale objects as arguments to functions, etc. </P>
<A NAME="idx555"><!></A>
<P>Locales are implemented using reference counting and the handle-body idiom: When a locale object is copied, only its handle is duplicated, a fast and inexpensive action. Similarly, constructing a locale object with the default constructor is cheap -- this is equivalent to copying the global locale object. All other locale constructors that take a second locale as an argument are moderately more expensive, because they require cloning the body of the locale object. However, the facets are not all copied. The byname constructor is the most expensive, because it requires creating the locale from an external locale representation.</P>
<P><A HREF="24-4.html#Figure&nbsp;10">Figure&nbsp;10</A> describes an overview of the locale architecture. It is a handle to a body that maintains a vector of pointers of facets. The facets are reference-counted, too.</P>
<A NAME="idx556"><!></A>
<H4><A NAME="Figure&nbsp;10">Figure&nbsp;10: The locale architecture</A></H4>
<P><IMG SRC="images/locfig10.gif" WIDTH=693 HEIGHT=509></P>
<BR>
<HR>
<A HREF="24-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,55 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The C and C++ Locales</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="23-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 24: The C and C++ Locales</H1>
<UL>
<UL><LI><A HREF="24-1.html">24.1 The C Locale</A></LI></UL>
<UL><LI><A HREF="24-2.html">24.2 The C++ Locales</A></LI></UL>
<UL><UL><LI><A HREF="24-2.html#2421">24.2.1 Facets</A></LI></UL></UL>
<UL><UL><UL><LI><A HREF="24-2.html#2421-1">24.2.1.1 The Standard Facets</A></LI></UL></UL></UL>
<UL><LI><A HREF="24-3.html">24.3 Differences between the C Locale and the C++ Locales</A></LI></UL>
<UL><UL><LI><A HREF="24-3.html#2431">24.3.1 Common Uses of the C locale</A></LI></UL></UL>
<UL><UL><LI><A HREF="24-3.html#2432">24.3.2 Common Uses of C++ Locales</A></LI></UL></UL>
<UL><UL><LI><A HREF="24-3.html#2433">24.3.3 The Relationship between the C Locale and the C++ Locale</A></LI></UL></UL>
<UL><LI><A HREF="24-4.html">24.4 The Locale Object</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="23-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="24-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,123 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Understanding Facet Types</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="25.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>25.1 Understanding Facet Types</H2>
<A NAME="idx557"><!></A>
<P>A <I>facet</I> is an object which can be stored in a locale and retrieved from the locale based on its type. Facets encapsulate data about cultural and language dependencies. They also contain services (functions) that use the encapsulated data to help you internationalize your programs.</P>
<A NAME="idx558"><!></A>
<P>The C++ Standard Library defines a number of facet classes, which we call <I>standard facets</I>. These facets were reviewed in the previous chapter; they are present in every locale. You can derive your own facet classes from the standard facets, to modify their behavior. You can also create entirely new facet classes, to handle aspects of internationalization that the standard facets don't cover. Both of these processes are described later in this chapter.</P>
<A NAME="idx559"><!></A>
<P>In talking about facet classes, we need to distinguish between <I>base facets</I> and <I>derived facets</I>. A <I>base facet</I> is a class with the following properties:</P>
<UL>
<LI><P CLASS="LIST">It is derived from class <SAMP>std::locale::facet</SAMP>.</P></LI>
<LI><P CLASS="LIST">It contains a static data member named <SAMP>id</SAMP>, of type <SAMP>std::locale::id</SAMP>.</P></LI>
</UL>
<P>These properties make it possible to store the facet in a locale, and to retrieve it from the locale based on its type. A locale contains at most one facet of each base facet type.</P>
<A NAME="idx560"><!></A>
<P>A <I>derived facet</I> is a class that is derived from a base facet, but does not contain its own static <SAMP>std::locale::id</SAMP> member. Instead, it inherits this member from the base facet it derives from. Like any facet, a derived facet can be stored in a locale, but it occupies the same <I>slot</I> in the locale as its base facet, displacing any other facet that was in that slot. For example, the following skeletal code defines a mythical base facet and a facet derived from it, and shows some of the ways these mythical facets can be stored in and retrieved from locales:</P>
<UL><PRE>
class mythical: public std::locale::facet { //1
public:
static std::locale::id id;
... // etc
};
std::locale::id mythical::id;
class mythical_byname: public mythical { //2
public:
mythical_byname (char *name,/*etc*/); // Constructor
... // etc
};
int main (void) {
std::locale loc0(std::locale::classic()); //3
std::locale loc1(loc0,new mythical); //4
std::locale loc2(loc1,new mythical_byname("he_DO")); //5
const mythical&amp; m2=std::use_facet&lt;mythical&gt;(loc2); //6
const mythical&amp; m1=std::use_facet&lt;mythical&gt;(loc1); //7
const mythical&amp; m0=std::use_facet&lt;mythical&gt;(loc0); //8
}
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>An example of a base facet class, derived from<SAMP> std::locale::facet</SAMP> and containing a static <SAMP>std::locale::id</SAMP> member name <SAMP>id</SAMP>.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>A derived facet class.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>A copy of the classic locale. Like all locales, it contains many facets. The facets are kept in <I>slots</I> indexed by the set of possible base facet types. Thus there is one slot for the base facet type <SAMP>mythical</SAMP>. In the classic locale, this <SAMP>mythical</SAMP> slot is empty.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>A copy of <SAMP>loc0</SAMP>, the classic locale, with its <SAMP>mythical</SAMP> slot now occupied by a newly-created <SAMP>mythical</SAMP> facet.
<TR VALIGN="top"><TD><SAMP>//5</SAMP></TD><TD>A copy of <SAMP>loc1</SAMP>, but with the <SAMP>mythical</SAMP> slot now occupied by a newly-created <SAMP>mythical_byname</SAMP> facet.
<TR VALIGN="top"><TD><SAMP>//6</SAMP></TD><TD>This returns a reference to the <SAMP>mythical_byname</SAMP> facet constructed in <SAMP>//5</SAMP>. However, note that you no longer know that it is a <SAMP>mythical_byname</SAMP> facet (short of using RTTI, which is cheating in this context). All you know is that it is a <SAMP>mythical</SAMP> facet, because it came from the <SAMP>mythical</SAMP> slot in the locale. (The <SAMP>std::use_facet</SAMP> function template is described in more detail later in this chapter.)
<TR VALIGN="top"><TD><SAMP>//7</SAMP></TD><TD>This returns a reference to the <SAMP>mythical</SAMP> facet constructed in step <SAMP>//4</SAMP>.
<TR VALIGN="top"><TD><SAMP>//8</SAMP></TD><TD>This causes a <SAMP>std::bad_cast</SAMP> exception to be thrown, because the <SAMP>mythical</SAMP> slot in <SAMP>loc0</SAMP> is empty.
</TABLE>
<A NAME="idx561"><!></A>
<P>The standard facets that come with the library are all defined as class templates. The first template parameter is always the character type the facet will operate on, which is usually <SAMP>char</SAMP> or <SAMP>wchar_t</SAMP>. Some of the facets have additional template parameters. As another example of the distinction between base facets and derived facets, here is a stripped-down version of the Standard facet template <SAMP>std::numpunct</SAMP>, which takes a single template parameter.</P>
<UL><PRE>
template &lt;class charT&gt;
class numpunct: public std::locale::facet {
public:
static std::locale::id id;
... // etc
};
template &lt;class charT&gt;
class numpunct_byname: public numpunct&lt;charT&gt; {
... // etc
};
</PRE></UL>
<A NAME="idx562"><!></A>
<P>Typically, these templates are instantiated on <SAMP>char</SAMP> and <SAMP>wchar_t</SAMP>, so the following are base facet types:</P>
<UL><PRE>
std::numpunct&lt;char&gt;
std::numpunct&lt;wchar_t&gt;
</PRE></UL>
<A NAME="idx563"><!></A>
<P>and the following are derived facet types:</P>
<UL><PRE>
std::numpunct_byname&lt;char&gt;
std::numpunct_byname&lt;wchar_t&gt;
</PRE></UL>
<P>If your application created its own character type <SAMP>my_char_t</SAMP>, then <SAMP>std::numpunct&lt;my_char_t&gt;</SAMP> would be a base facet type and <SAMP>std::numpunct_byname&lt;my_char_t&gt;</SAMP> would be a derived facet type.</P>
<BR>
<HR>
<A HREF="25.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,105 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Facet Lifetimes</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="25-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>25.2 Facet Lifetimes</H2>
<A NAME="idx564"><!></A>
<P>In the <SAMP>mythical</SAMP> example in the previous section, we created two facet objects with operator <SAMP>new</SAMP> and incorporated them into locales, but we never deleted the facets with operator <SAMP>delete</SAMP>. This is poor coding for most objects, but for facet objects it is correct. Once a facet has been incorporated into a locale, the locale system takes over responsibility for deleting the facet when it is no longer needed, that is, when all locales that contain references to it have been destroyed.</P>
<A NAME="idx565"><!></A>
<P>This is a useful feature. For example, consider the following fragment:</P>
<UL><PRE>
using namespace std;
cout.imbue(locale(locale(),new numpunct_byname&lt;char&gt;("de_DE")));
| | | |
(4) (3) (1) (2)
</PRE></UL>
<P>What's happening here is fairly complex, so let's trace it out step by step: </P>
<OL>
<LI><P CLASS="LIST">We create a temporary locale object that is a copy of the current global locale.</P></LI>
<LI><P CLASS="LIST">We create a <SAMP>std::numpunct</SAMP> facet for a German locale.</P></LI>
<LI><P CLASS="LIST">We create another temporary locale which is a copy of the one created in <SAMP>(1)</SAMP>, but with its <SAMP>std::numpunct</SAMP> facet replaced by the facet created in <SAMP>(2)</SAMP>. </P></LI>
<LI><P CLASS="LIST">Using locale's copy constructor, we pass this locale by value to <SAMP>std::cout.imbue</SAMP>, which saves a copy of it in the stream object.</P></LI>
</OL>
<A NAME="idx566"><!></A>
<P>At the end of this operation, all the temporary objects are quietly destroyed, but a reference to the new <SAMP>std::numpunct</SAMP> facet remains behind in the locale object inside <SAMP>std::cout</SAMP>. Other functions can retrieve this object using <SAMP>std::cout.getloc()</SAMP>, and make copies of it and its facets. All in all, it would be a burden on an application to have to keep track of all this, in order to determine when it is safe to delete the <SAMP>std::numpunct_byname</SAMP> object. We can be grateful that the locale system takes care of this chore.</P>
<A NAME="idx567"><!></A>
<P>It is possible, but not recommended, to override this default behavior. The constructors of all the standard facets, and the constructor of the base class <SAMP>std::locale::facet</SAMP>, all take an integer parameter named <SAMP>refs</SAMP>, which defaults to <SAMP>0</SAMP> when you don't specify it. This is the usual case. If you specify it as <SAMP>1</SAMP> or some other positive integer, the locale system does not delete the facet.</P>
<A NAME="idx568"><!></A>
<P>This is necessary for facet objects that can't have the <SAMP>delete</SAMP> operator applied to them, for instance, because they were created on the stack or as static objects. To discourage you from creating facets this way, all the standard facets have protected destructors. The following code causes a compilation error:</P>
<UL><PRE>
static std::numpunct&lt;char&gt; my_static_np(1); // Error: no public
// destructor
int main () {
std::numpunct_byname&lt;char&gt; my_np("de_DE",1); // Error: no public
// destructor
...
}
</PRE></UL>
<A NAME="idx569"><!></A>
<P>You can circumvent this protection by deriving a class with a public destructor from the standard facet. This may seem reasonable if you are going to use it only as a stand-alone object, and do not plan to incorporate it into any locale. For example, the following code lets you retrieve some data from the standard <SAMP>std::numpunct&lt;char&gt;</SAMP> facet without the overhead of <SAMP>new/delete</SAMP>:</P>
<UL><PRE>
class my_numpunct: public std::numpunct&lt;char&gt; { };
int main() {
my_numpunct np;
std::cout &lt;&lt; np.truename() &lt;&lt; " or " &lt;&lt; np.falsename()
&lt;&lt; '?' &lt;&lt; std::endl;
...
}
</PRE></UL>
<P>However, the following code accomplishes the same thing even faster, because <SAMP>use_facet</SAMP> is very fast compared to the cost of calling most facets' constructors:</P>
<UL><PRE>
int main() {
const std::numpunct&lt;char&gt;&amp; np=
std::use_facet&lt;numpunct&lt;char&gt; &gt;(std::locale::classic());
std::cout &lt;&lt; np.truename() &lt;&lt; " or " &lt;&lt; np.falsename()
&lt;&lt; '?' &lt;&lt; std::endl;
...
}
</PRE></UL>
<A NAME="idx570"><!></A>
<P>In short, while it is possible to create facet objects on the stack, there is rarely a reason to do so. It is probably better to adapt a consistent policy of always creating facet objects with operator <SAMP>new</SAMP>. If you incorporate the facet into a locale, you do not need to delete it, and indeed, deleting it would be an error. If you never incorporate it into any locale, you should delete it when you are finished with it. Instead of creating and deleting a stand-alone facet in this case, however, it is usually possible (and faster) to accomplish the same thing by retrieving a reference to an existing facet from some locale.</P>
<BR>
<HR>
<A HREF="25-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,87 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Accessing a Locale's Facets</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="25-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>25.3 Accessing a Locale's Facets</H2>
<A NAME="idx571"><!></A>
<P>A locale object is like a container or a map, to be more precise, but it is indexed by type at compile time. The indexing operator, therefore, is not the subscript operator <SAMP>operator[]()</SAMP>, but rather the template operator <SAMP>&lt;&gt;</SAMP>. Access to the facet objects of a locale object is via two member function templates, <SAMP>use_facet()</SAMP> and <SAMP>has_facet()</SAMP>:</P>
<UL><PRE>
template&lt;class Facet&gt; const Facet&amp; use_facet(const locale&amp;);
template&lt;class Facet&gt; bool has_facet(const locale&amp;);
</PRE></UL>
<A NAME="idx572"><!></A>
<P>The code below demonstrates how they are used. It is an example of the <SAMP>ctype</SAMP> facet's usage; all upper case letters of a string read from the standard input stream are converted to lower case letters and written to the standard output stream.</P>
<UL><PRE>
std::string in;
std::cin &gt;&gt; in;
if (std::has_facet&lt; ctype&lt;char&gt; &gt;(std::locale())) //1
{
std::cout &lt;&lt; use_facet&lt;ctype&lt;char&gt; &gt;(std::locale()) //2
.tolower(in.begin(),in.end()); //3
}
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>In the call to <SAMP>has_facet&lt;...&gt;()</SAMP>, the template argument chooses a base facet class. If no facet of this type is present in a locale object, <SAMP>has_facet</SAMP> returns <SAMP>false</SAMP>.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>The function template <SAMP>use_facet&lt;...&gt;()</SAMP> returns a reference to the locale's facet object of the specified base facet type. As locale objects are immutable, the reference stays valid throughout the lifetime of the locale object. If no facet of the specified type is present in the locale, <SAMP>use_facet</SAMP> throws a <SAMP>runtime_error</SAMP> exception.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>The facet object's member function <SAMP>tolower()</SAMP> is called. It has the functionality of the C function <SAMP>tolower()</SAMP>; it converts all upper case letters in the string into lower case letters.
</TABLE>
<P>In this example, the call to <SAMP>has_facet</SAMP> is actually unnecessary because <SAMP>ctype&lt;char&gt;</SAMP> is a standard facet. Every locale always contains a complete complement of the standard facets, so <SAMP>has_facet&lt;ctype&lt;char&gt; &gt;</SAMP> always returns <SAMP>true</SAMP>. However, a call to <SAMP>has_facet()</SAMP> can be useful when you are dealing with nonstandard facets, such as the <SAMP>mythical</SAMP> facet described earlier in this chapter, which may not be present in every locale.</P>
<A NAME="idx573"><!></A>
<P>When you are coding <SAMP>use_facet</SAMP> and <SAMP>has_facet</SAMP> calls, it is important that the facet type you specify as the template parameter is a base facet type, and not a derived facet type. The following is an error:</P>
<UL><PRE>
locale loc;
const std::numpunct_byname&lt;char&gt;&amp; np = // Error, use_facet
use_facet&lt;std::numpunct_byname&lt;char&gt; &gt;(loc); // instantiated on
// a non-base facet
// type
</PRE></UL>
<P>Depending on the facet type, and on your compiler, this will probably cause a compile-time error. If it does not, it may result in unpredictable runtime behavior. The <SAMP>use_facet</SAMP> call returns the facet that occupies the slot for the type <SAMP>std::numpunct_byname&lt;char&gt;</SAMP>. But in fact, as described earlier, this is the same as the slot for the base facet type, <SAMP>std::numpunct&lt;char&gt;</SAMP>. So the above code may cause <SAMP>np</SAMP> to be initialized to a reference to an object that is not, in fact, of type <SAMP>std::numpunct_byname&lt;char&gt;</SAMP>.</P>
<P>To avoid errors like this, make sure that you only instantiate <SAMP>use_facet</SAMP> and <SAMP>has_facet</SAMP> on base facet types, that is, on facet types that contain a static <SAMP>locale::id</SAMP> member.</P>
<UL><PRE>
locale loc;
const numpunct&lt;char&gt;&amp; np = // Correct
use_facet&lt;numpunct&lt;char&gt; &gt;(loc);
</PRE></UL>
<BR>
<HR>
<A HREF="25-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,133 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Using a Stream's Facet</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="25-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-5.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>25.4 Using a Stream's Facet</H2>
<A NAME="idx574"><!></A>
<A NAME="idx575"><!></A>
<P>Here is a more advanced example that uses a <SAMP>std::time_put</SAMP> facet to print a date. Let us assume we have a date and want to print it this way:</P>
<UL><PRE>
struct std::tm aDate; //1
std::memset(aDate,0,sizeof aDate); //2
aDate.tm_year = 1989;
aDate.tm_mon = 9;
aDate.tm_mday = 1;
std::cout.imbue(std::locale("De_CH")); //3
std::cout &lt;&lt; aDate; //4
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>A date object is created. It is of type <SAMP>std::tm</SAMP>, which is the time structure defined in <SAMP>&lt;ctime&gt;</SAMP>.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>The date object is initialized with a particular date, September 1, 1989.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>Let's assume our program is supposed to run in a German-speaking canton of Switzerland. Hence, we imbue the standard output stream with a German-Swiss locale.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>The date is printed in German to the standard output stream.
</TABLE>
<P>The output is: <SAMP>1. September 1989</SAMP></P>
<A NAME="idx576"><!></A>
<P>As there is no <SAMP>operator&lt;&lt;()</SAMP> defined in the C++ Standard Library for the time structure <SAMP>tm</SAMP> from the C library, we must provide this inserter ourselves. The following code suggests a way this can be done. If you are not familiar with iostreams, please refer to the iostreams part of this <I>User's </I><I>Guide</I>. </P>
<P>To keep it simple, the handling of exceptions thrown during the formatting is omitted.</P>
<UL><PRE>
template&lt;class charT, class traits&gt;
std::basic_ostream&lt;charT, traits&gt;&amp;
operator&lt;&lt;(std::basic_ostream&lt;charT,traits&gt;&amp; os,
const std::tm&amp; date) //1
{
std::locale loc = os.getloc(); //2
typedef std::ostreambuf_iterator&lt;charT,traits&gt;
outIter_t; //3
const std::time_put&lt;charT,outIter_t&gt;&amp; fac //4
= std::use_facet&lt;std::time_put&lt;charT,
outIter_t&gt; &gt;(loc); //5
fac.put(os,os,os.fill(),&amp;date,'x'); //6
return os;
}
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>This is a typical signature of a stream inserter; it takes a reference to an output stream and a constant reference to the object to be printed, and returns a reference to the same stream.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>The stream's locale object is obtained via the stream's member function <SAMP>getloc()</SAMP>. This is the locale object where we expect to find a time-formatting facet object.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>We define a type for an output iterator to a stream buffer.
Time-formatting facet objects write the formatted output via an iterator into an output container (see the sections on containers and iterators in the <I>C++ Standard Library</I> <I>User's Guide</I>). In principle, this can be an arbitrary container that has an output iterator, such as a string or a C++ array.
Here we want the time-formatting facet object to bypass the stream's formatting layer and write directly to the output stream's underlying stream buffer. Therefore, the output container shall be a stream buffer.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>We define a variable that will hold a reference to the locale object's <SAMP>std::time_put</SAMP> facet object. The time formatting facet class <SAMP>std::time_put</SAMP> has two template parameters:
<UL>
<LI><P CLASS="LIST">The <I>first</I> template parameter is the character type used for output. Here we provide the stream's character type as the template argument.</P></LI>
<LI><P CLASS="LIST">The <I>second</I> template parameter is the output iterator type. Here we provide the stream buffer iterator type <SAMP>outIter_t</SAMP> that we had defined as before.</P></LI>
</UL>
<TR VALIGN="top"><TD><SAMP>//5</SAMP></TD><TD>Here we get the time-formatting facet object from the stream's locale via <SAMP>std::use_facet()</SAMP>.
<TR VALIGN="top"><TD><SAMP>//6</SAMP></TD><TD>The facet object's formatting service <SAMP>put()</SAMP> is called. Let us see what arguments it takes. Here is the function's interface:</P>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="3">
<TR><TD VALIGN="top"><P><SAMP>iter_type put</SAMP></P>
</TD><TD VALIGN="top"><P><SAMP>(iter_type</SAMP></P>
</TD><TD VALIGN="top"><P><SAMP>(a)</SAMP></P>
</TD></TR>
<TR><TD VALIGN="top">&nbsp;</TD><TD VALIGN="top"><P><SAMP>,ios_base&amp;</SAMP></P>
</TD><TD VALIGN="top"><P><SAMP>(b)</SAMP></P>
</TD></TR>
<TR><TD VALIGN="top">&nbsp;</TD><TD VALIGN="top"><P><SAMP>,char_type</SAMP></P>
</TD><TD VALIGN="top"><P><SAMP>(c)</SAMP></P>
</TD></TR>
<TR><TD VALIGN="top">&nbsp;</TD><TD VALIGN="top"><P><SAMP>,const tm*</SAMP></P>
</TD><TD VALIGN="top"><P><SAMP>(d)</SAMP></P>
</TD></TR>
<TR><TD VALIGN="top">&nbsp;</TD><TD VALIGN="top"><P><SAMP>,char)</SAMP></P>
</TD><TD VALIGN="top"><P><SAMP>(e)</SAMP></P>
</TD></TR>
</TABLE>
The types <SAMP>iter_type</SAMP> and <SAMP>char_type</SAMP> stand for the types that were provided as template arguments when the facet class was instantiated. In this case, they are <B><I><A HREF="../stdlibref/ostreambuf-iterator.html">std::ostreambuf_iterator&lt;&gt;</A></I></B> and <SAMP>charT</SAMP>, where <SAMP>charT</SAMP> and <SAMP>traits</SAMP> are the respective streams template arguments.
Here is the actual call:
<SAMP>nextpos = fac.put(os,os,os.fill(),&amp;date,'x');</SAMP>
Now let's see what the arguments mean:
<TABLE CELLPADDING=3>
<TR CLASS="LIST"><TD VALIGN="top" CLASS="LIST"><P CLASS="LIST">a.</P></TD><TD CLASS="LIST"><P CLASS="LIST">The first parameter is supposed to be an output iterator. We provide an iterator to the stream's underlying stream buffer. The reference <SAMP>os</SAMP> to the output stream is converted to an output iterator, because output stream buffer iterators have a constructor taking an output stream, that is, <B><I>basic_ostream&lt;&gt;&amp;</I></B>.</P></TD></TR>
<TR CLASS="LIST"><TD VALIGN="top" CLASS="LIST"><P CLASS="LIST">b.</P></TD><TD CLASS="LIST"><P CLASS="LIST">The second parameter is of type <B><I><A HREF="../stdlibref/ios-base.html">ios_base</A></I></B><SAMP>&amp;</SAMP>, which is one of the stream base classes. The class <B><I>ios_base</I></B> contains data for format control (see the section on iostreams for details). The facet object uses this formatting information. We provide the output stream's <B><I>ios_base</I></B> part here, using the automatic cast from a reference to an output stream, to a reference to its base class.</P></TD></TR>
<TR CLASS="LIST"><TD VALIGN="top" CLASS="LIST"><P CLASS="LIST">c.</P></TD><TD CLASS="LIST"><P CLASS="LIST">The third parameter is the fill character. It is used when the output has to be adjusted and blank characters have to be filled in. We provide the stream's fill character, which one can get by calling the stream's <SAMP>fill()</SAMP> function.</P></TD></TR>
<TR CLASS="LIST"><TD VALIGN="top" CLASS="LIST"><P CLASS="LIST">d.</P></TD><TD CLASS="LIST"><P CLASS="LIST">The fourth parameter is a pointer to a time structure <SAMP>std::tm</SAMP> defined in <SAMP>&lt;ctime&gt;</SAMP>.</P></TD></TR>
<TR CLASS="LIST"><TD VALIGN="top" CLASS="LIST"><P CLASS="LIST">e.</P></TD><TD CLASS="LIST"><P CLASS="LIST">The fifth parameter is a format character as in the C function <SAMP>std::strftime()</SAMP>; the <SAMP>x</SAMP> stands for the locale's appropriate date representation.</P></TD></TR>
</TABLE>
The value returned is an output iterator that points to the position immediately after the last inserted character.
</TABLE>
<BR>
<HR>
<A HREF="25-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-5.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,144 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Modifying a Standard Facet's Behavior</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="25-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-6.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>25.5 Modifying a Standard Facet's Behavior</H2>
<A NAME="idx577"><!></A>
<P>At times you may need to replace a facet object in a locale by another kind of facet object. In the following example, let us derive from one of the standard facet classes, <B><I><A HREF="../stdlibref/numpunct.html">numpunct</A></I></B>, and create a locale object in which the standard <SAMP>std::numpunct</SAMP> facet object is replaced by an instance of our new, derived facet class. </P>
<P>Here is the problem we want to solve. When you print Boolean values, you can choose between the numeric representation of the values <SAMP>"true"</SAMP> and <SAMP>"false"</SAMP>, or their alphanumeric representation. </P>
<UL><PRE>
int main(int argc, char** argv)
{
bool any_arguments = (argc &gt; 1); //1
std::cout.setf(ios_base::boolalpha); //2
std::cout &lt;&lt; any_arguments &lt;&lt; '\n'; //3
// ...
}
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>A variable of type <SAMP>bool</SAMP> is defined. Its initial value is the boolean value of the logical expression <SAMP>(argc &gt; 1)</SAMP>, so the variable <SAMP>any_arguments</SAMP> contains the information, whether the program was called with or without arguments.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>The format flag <SAMP>std::ios_base::boolalpha</SAMP> is set in the predefined output stream <SAMP>cout</SAMP>. The effect is that the string representation of boolean values is printed, instead of their numerical representation <SAMP>0</SAMP> or <SAMP>1</SAMP>, which is the default representation.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>Here either the string <SAMP>"true"</SAMP> or the string <SAMP>"false"</SAMP> are printed.
</TABLE>
<P>Of course, the string representation depends on the language. Hence, the alphanumeric representation of boolean values is provided by a locale. It is the <SAMP>std::numpunct</SAMP> facet of a locale that describes the cultural conventions for numerical formatting. It contains services that return the string representations of the boolean values <SAMP>true</SAMP> and <SAMP>false</SAMP>.</P>
<A NAME="idx578"><!></A>
<P>This is the interface of facet <B><I><A HREF="../stdlibref/numpunct.html">numpunct</A></I></B>:</P>
<UL><PRE>
namespace std{
template &lt;class charT&gt;
class numpunct : public locale::facet {
public:
typedef charT char_type;
typedef basic_string&lt;charT&gt; string_type;
explicit numpunct(size_t refs = 0);
char_type decimal_point() const;
char_type thousands_sep() const;
string grouping() const;
string_type <I>truename</I>() const;
string_type <I>falsename</I>() const;
static locale::id id;
// ...
};
}
</PRE></UL>
<A NAME="idx579"><!></A>
<P>Now let us replace this facet. To make it more exciting, let's use not only a different language, but also different words for <SAMP>true</SAMP> and <SAMP>false</SAMP>, such as <SAMP>Yes!</SAMP> and <SAMP>No!</SAMP>. For just using another language, we would not need a new facet; we would simply use the right native locale, and it would contain the right facet.</P>
<UL><PRE>
template &lt;class charT&gt; //1
class change_bool_names
: public std::numpunct_byname&lt;charT&gt; //2
{
public:
typedef std::basic_string&lt;charT&gt; string_type;
explicit change_bool_names (const char* name, //3
const charT* t,
const charT* f, size_t refs=0)
: std::numpunct_byname&lt;charT&gt; (name,refs),
true_string(t), false_string(f) { }
protected:
virtual string_type do_truename() const { //4
return true_string;
}
virtual string_type do_falsename() const {
return false_string;
}
private:
string_type true_string, false_string;
};
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>The new facet is a class template that takes the character type as a template parameter.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>The new facet is derived from the <SAMP>std::numpunct_byname&lt;charT&gt;</SAMP> facet.
<BR><BR>The byname facets read the respective locale information from the external representation of a C locale. The name provided to construct a byname<I> </I>facet is the name of a locale, as you would use it in a call to <SAMP>setlocale()</SAMP>.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>A constructor is provided that takes a locale name and the new values we want to display for the alpha versions of <SAMP>true</SAMP> and <SAMP>false</SAMP>. The fourth parameter, <SAMP>refs</SAMP>, controls the facet's lifetime, as described in an earlier section.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>The virtual member functions <SAMP>do_truename()</SAMP> and <SAMP>do_falsename()</SAMP> are reimplemented. They are called by the public member functions <SAMP>truename()</SAMP> and <SAMP>falsename()</SAMP>. See the <A HREF="../stdlibref/noframes.html"><I>Apache C++ Standard Library Reference Guide</I></A> for further details.
</TABLE>
<P>Now let's create a German locale in which the <SAMP>std::numpunct&lt;char&gt;</SAMP> facet has been replaced by an object of our new derived facet type, as shown in <A HREF="25-5.html#Figure&nbsp;11">Figure&nbsp;11</A>:</P>
<A NAME="idx580"><!></A>
<H4><A NAME="Figure&nbsp;11">Figure&nbsp;11: Replacing the std::numpunct&lt;char&gt; facet object</A></H4>
<P><IMG SRC="images/locfig12.gif" WIDTH=476 HEIGHT=311></P>
<A NAME="idx581"><!></A>
<P>The code looks like this:</P>
<UL><PRE>
void main(int argc, char** argv)
{
std::locale loc(std::locale("de_DE"), //1
new change_bool_names&lt;char&gt;("de_DE","Ja.","Nein.")); //2
std::cout.imbue(loc); //3
std::cout &lt;&lt; "Argumente vorhanden? " //Any arguments?
&lt;&lt; std::boolalpha &lt;&lt; (argc &gt; 1) &lt;&lt; std::endl; //4
}
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>A locale object is constructed with an instance of the new facet class. The locale object has all facet objects from a German locale object, except that the new facet object <SAMP>change_bool_names</SAMP> substitutes for the <SAMP>std::numpunct</SAMP> facet object<SAMP>.</SAMP>
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>The new facet object takes all information from a German <SAMP>numpunct</SAMP> facet object, and replaces the default native names for <SAMP>true</SAMP> and <SAMP>false</SAMP> with the provided strings <SAMP>"Ja."</SAMP> ("Yes.") and <SAMP>"Nein."</SAMP> ("No.").
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>The standard output stream <SAMP>std::cout</SAMP> is imbued with the newly created locale.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>The expression <SAMP>(argc &gt; 1)</SAMP> yields a boolean value, which indicates whether the program was called with arguments. This boolean value's alphanumeric representation is printed to the standard output stream. The output might be:
<BR><BR><SAMP>Argument vorhanden? Ja.</SAMP>
</TABLE>
<BR>
<HR>
<A HREF="25-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-6.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,93 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Creating a New Base Facet Class</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="25-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>25.6 Creating a New Base Facet Class</H2>
<A NAME="idx582"><!></A>
<P>At times you may need to add a facet object to a locale without displacing any of the existing facets. To do this, you must define a new base facet class.</P>
<P>Here is an example of a new facet class like that. It is a facet that provides a service to check whether a character is a German umlaut, that is, one of the special characters <SAMP>&auml;&ouml;&uuml;&Auml;&Ouml;&Uuml;</SAMP>.</P>
<UL><PRE>
class Umlaut : public std::locale::facet { //1
public:
static std::locale::id id; //2
Umlaut(std::size_t refs=0): std::locale::facet(refs) {} //3
bool is_umlaut(char c) const {return do_isumlaut(c);} //4
protected:
virtual bool do_isumlaut(char) const; //5
};
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>All base facet classes must be derived from class <SAMP>std::locale::facet</SAMP>.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>In addition, all base facet classes must contain a static member named <SAMP>id</SAMP>, of type <SAMP>std::locale::id</SAMP>. The locale system uses this object internally to identify the slot in locale objects where facets of this type are stored.
<BR><BR>(Derived facet classes do not contain their own <SAMP>id</SAMP> members. Instead, they inherit the member from a base facet class, and therefore are stored in the same slot as the base class.)
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>A <SAMP>const</SAMP> member function <SAMP>is_umlaut()</SAMP> is declared that returns the result of calling the protected virtual const function <SAMP>do_umlaut()</SAMP>. All facet member functions must be const since like locale objects, facets are immutable. Since the function template <SAMP>std::use_facet&lt;&gt;() </SAMP>returns a <SAMP>const </SAMP>reference to a facet, only member functions declared <SAMP>const</SAMP> are callable.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>A member function <SAMP>is_umlaut()</SAMP> is declared that returns the result of calling the protected virtual function <SAMP>do_umlaut()</SAMP>.
<TR VALIGN="top"><TD><SAMP>//5</SAMP></TD><TD>The actual functionality of determining whether a character is an umlaut is implemented in a protected virtual member function. In general, all localization services in a facet should be implemented in virtual functions this way, so that derived facets can override them when necessary.
</TABLE>
<A NAME="idx583"><!></A>
<P>Now let's create a locale with a facet of the new type, as shown in <A HREF="25-6.html#Figure&nbsp;12">Figure&nbsp;12</A>:</P>
<A NAME="idx584"><!></A>
<H4><A NAME="Figure&nbsp;12">Figure&nbsp;12: Adding a new facet to a locale</A></H4>
<P><IMG SRC="images/locfig13.gif" WIDTH=419 HEIGHT=317></P>
<P>The code for this procedure is given below:</P>
<UL><PRE>
std::locale loc(std::locale(""), // native locale
new Umlaut); // the new facet //1
char c,d;
while (std::cin &gt;&gt; c){
d = std::use_facet&lt;std::ctype&lt;char&gt; &gt;(loc).tolower(c); //2
if (std::has_facet&lt;Umlaut&gt;(loc)) { //3
if (std::use_facet&lt;Umlaut&gt;(loc).is_umlaut(d)) //4
std::cout &lt;&lt; c &lt;&lt; "belongs to the German alphabet!" &lt;&lt; '\n';
}
}
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>A locale object is constructed with an instance of the new facet class. The locale object has all facet objects from the native locale object, plus an instance of the new facet class <SAMP>Umlaut</SAMP>.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>Let's assume our new umlaut facet class is somewhat limited; it can handle only lower case characters. Thus we have to convert each character to a lower case character before we hand it over to the umlaut facet object. This is done by using a <SAMP>std::ctype</SAMP> facet object's service function <SAMP>tolower()</SAMP>.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>Before we use the umlaut facet object, we check whether such an object is present in the locale. In a toy example like this it is obvious, but in a real application it is advisable to check for the existence of nonstandard facet objects before trying to use them.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>The umlaut facet object is used, and its member function <SAMP>is_umlaut()</SAMP> is called. Note that the syntax for using this newly contrived facet object is exactly like the syntax for using the standard <SAMP>ctype</SAMP> facet.
</TABLE>
<BR>
<HR>
<A HREF="25-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,52 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>Facets</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="24-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-1.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H1>Chapter 25: Facets</H1>
<UL>
<UL><LI><A HREF="25-1.html">25.1 Understanding Facet Types</A></LI></UL>
<UL><LI><A HREF="25-2.html">25.2 Facet Lifetimes</A></LI></UL>
<UL><LI><A HREF="25-3.html">25.3 Accessing a Locale's Facets</A></LI></UL>
<UL><LI><A HREF="25-4.html">25.4 Using a Stream's Facet</A></LI></UL>
<UL><LI><A HREF="25-5.html">25.5 Modifying a Standard Facet's Behavior</A></LI></UL>
<UL><LI><A HREF="25-6.html">25.6 Creating a New Base Facet Class</A></LI></UL>
</UL>
<BR>
<HR>
<A HREF="24-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="25-1.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,84 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>An Example of Formatting Phone Numbers</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="26.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-2.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>26.1 An Example of Formatting Phone Numbers</H2>
<A NAME="idx585"><!></A>
<A NAME="idx586"><!></A>
<P>The previous chapters explained how you can use locales and the standard facet classes, and how you can build new facet classes. This chapter introduces you to the technique of building your own facet class and using it in conjunction with the input/output streams of the C++ Standard Library, the iostreams. This material is rather advanced, and requires some knowledge of standard iostreams.</P>
<A NAME="idx587"><!></A>
<P>In the following sections, we will work through a complete example on formatting telephone numbers. Formatting telephone numbers involves local conventions that vary from culture to culture. For example, the same US phone number can have all of the formats listed below:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">754-3010</P>
</td><td valign=top><P CLASS="TABLE">Local</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">(541) 754-3010</P>
</td><td valign=top><P CLASS="TABLE">Domestic</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">+1-541-754-3010</P>
</td><td valign=top><P CLASS="TABLE">International</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">1-541-754-3010</P>
</td><td valign=top><P CLASS="TABLE">Dialed in the US</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">001-541-754-3010</P>
</td><td valign=top><P CLASS="TABLE">Dialed from Germany</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">191 541 754 3010</P>
</td><td valign=top><P CLASS="TABLE">Dialed from France</P>
</td></tr>
</TABLE>
<P>Now consider a German phone number. Although a German phone number consists of an area code and an extension like a US number, the format is different. Here is the same German phone number in a variety of formats:</P>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3">
<tr><td valign=top><P CLASS="TABLE">636-48018</P>
</td><td valign=top><P CLASS="TABLE">Local</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">(089) / 636-48018</P>
</td><td valign=top><P CLASS="TABLE">Domestic</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">+49-89-636-48018</P>
</td><td valign=top><P CLASS="TABLE">International</P>
</td></tr>
<tr><td valign=top><P CLASS="TABLE">19-49-89-636-48018</P>
</td><td valign=top><P CLASS="TABLE">Dialed from France</P>
</td></tr>
</TABLE>
<P>Note the difference in formatting domestic numbers. In the US, the convention is <SAMP>1 (area code) extension</SAMP>, while in Germany it is <SAMP>(0 area code)/extension</SAMP>.</P>
<BR>
<HR>
<A HREF="26.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-2.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,64 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>A Phone Number Class</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="26-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-3.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>26.2 A Phone Number Class</H2>
<P>An application that has to handle phone numbers will probably have a class that represents a phone number. We will also want to read and write telephone numbers via iostreams, and therefore define suitable extractor and inserter functions. For the sake of simplicity, we will focus on the inserter function in our example.</P>
<A NAME="idx588"><!></A>
<P>To begin, here is the complete class declaration for the telephone number class <SAMP>PhoneNumber</SAMP>:</P>
<UL><PRE>
struct PhoneNumber
{
typedef std::string string_type;
PhoneNumber (const string_type cntryName,
const string_type areaCode,
const string_type extension)
: _cntryName (cntryName), _areaCode (areaCode),
_extension (extension) {}
string_type _cntryName; // "US"
string_type _areaCode; // "303"
string_type _extension; // "545-3200"
};
</PRE></UL>
<BR>
<HR>
<A HREF="26-1.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-3.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,75 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>A Phone Number Formatting Facet Class</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="26-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-4.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>26.3 A Phone Number Formatting Facet Class</H2>
<P>Now that we have locales and facets in C++, we can encapsulate the locale-dependent parsing and formatting of telephone numbers into a new facet class. Let's focus on formatting in this example. We call the new facet class <SAMP>phone_put</SAMP>, analogous to <SAMP>time_put</SAMP>, <SAMP>money_put</SAMP>, etc.</P>
<A NAME="idx589"><!></A>
<P>The <SAMP>phone_put</SAMP> facet class serves solely as a base class for facet classes that actually implement the locale-dependent formatting. The relationship of class <SAMP>phone_put</SAMP> to the other facet classes is illustrated in <A HREF="26-3.html#Figure&nbsp;13">Figure&nbsp;13</A>:</P>
<A NAME="idx590"><!></A>
<H4><A NAME="Figure&nbsp;13">Figure&nbsp;13: The relationship of the phone_put facet to the implementing facets</A></H4>
<P><IMG SRC="images/stdlibug-Locales11.gif" WIDTH=555 HEIGHT=226></P>
<A NAME="idx591"><!></A>
<P>Here is a first tentative declaration of the new facet class <SAMP>phone_put</SAMP>:</P>
<UL><PRE>
class phone_put: public std::locale::facet { // 1
public:
static std::locale::id id; // 2
typedef std::string string_type;
phone_put (std::size_t refs = 0)
: std::locale::facet (refs) { } // 3
string_type put (const string_type &amp;cntryName,
const string_type &amp;areaCode,
const string_type &amp;extension) const; // 4
};
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>Derive from the base class <SAMP>std::locale::facet</SAMP>, so that a locale object is able to maintain instances of our new phone facet class.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>New base facet classes need to define a static data member <SAMP>id</SAMP> of type <SAMP>std::locale::id</SAMP>.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>Define a constructor that takes the reference count that is handed over to the base class.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>Define a function <SAMP>put()</SAMP> that does the actual formatting.
</TABLE>
<BR>
<HR>
<A HREF="26-2.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-4.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,62 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>An Inserter for Phone Numbers</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="26-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-5.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>26.4 An Inserter for Phone Numbers</H2>
<A NAME="idx592"><!></A>
<P>Now let's take a look at the implementation of the inserter for our phone number class:</P>
<UL><PRE>
std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const PhoneNumber&amp; pn){
std::locale loc = os.getloc (); // 1
const phone_put&amp; ppFacet
= std::use_facet&lt;phone_put&gt; (loc); // 2
os &lt;&lt; ppFacet.put(pn._cntryName,
pn._areaCode, pn._extension); // 3
return (os);
}
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>The inserter function uses the output stream's locale object (obtained via <SAMP>getloc()</SAMP>),
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>uses the locale's phone number facet object,
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>and calls the facet object's formatting service <SAMP>put()</SAMP>.
</TABLE>
<BR>
<HR>
<A HREF="26-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-5.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,183 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>The Phone Number Facet Class Revisited</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="26-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-6.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>26.5 The Phone Number Facet Class Revisited</H2>
<A NAME="idx593"><!></A>
<P>Let us now try to implement the phone number facet class. What does this facet need to know?</P>
<UL>
<LI><P CLASS="LIST">A facet needs to know its own locality, because a phone number is formatted differently for domestic and international use; for example, a German number looks like (089) / 636-48018 when used in Germany, but it looks like +1-49-89-636-48018 when used internationally.</P></LI>
<LI><P CLASS="LIST">A facet needs information about the prefix for dialing international numbers; for example, 011 for dialing foreign numbers from the US, or 00 from Germany, or 19 from France.</P></LI>
<LI><P CLASS="LIST">A facet needs access to a table of all country codes, so that one can enter a mnemonic for the country instead of looking up the respective country code. For example, I would like to say: "This is a phone number somewhere in Japan" without having to know what the country code for Japan is.</P></LI>
</UL>
<A NAME="idx594"><!></A>
<A NAME="2651"><H3>26.5.1 Adding Data Members</H3></A>
<A NAME="idx595"><!></A>
<P>The following class declaration for the telephone number formatting facet class is enhanced with a virtual member function <SAMP>do_put()</SAMP> which is delegated the task of actually constructing a phone number in a locale-dependent fashion in derived classes, as well as data members for the facet object's own locality, and its prefix for international calls (see <SAMP>//4</SAMP> and <SAMP>//5</SAMP> in the code below). Adding a table of country codes is omitted for the time being.</P>
<UL><PRE>
class phone_put: public std::locale::facet {
public:
static std::locale::id id;
typedef std::string string_type;
phone_put (std::size_t refs = 0)
: std::locale::facet (refs) { }
string_type put (const string_type &amp;cntryName,
const string_type &amp;areaCode,
const string_type &amp;extension) const {
return do_put (cntryName, areaCode, extension); // 1
}
protected:
phone_put (const string_type cntryName,
const string_type intlPrefix,
std::size_t refs = 0) // 2
: std::locale::facet(refs),
_cntryName(cntryName), _intlPrefix(intlPrefix);
virtual string_type
do_put(const string_type &amp;cntryName, // 3
const string_type &amp;areaCode,
const string_type &amp;extension) const { ... }
const string_type _cntryName; // 4
const string_type _intlPrefix; // 5
};
</PRE></UL>
<P>Note how this class serves as a base class for the facet classes that really implement a locale-dependent phone number formatting. Hence, the public constructor does not need to be extended, and a protected constructor is added instead (see <SAMP>//2</SAMP> above). The virtual member function <SAMP>do_put()</SAMP> is added (see <SAMP>//3</SAMP> above) so that it may be overridden in derived classes without hiding any overloads of the <SAMP>put()</SAMP> function if they existed, and also so that code can be placed in <SAMP>put()</SAMP> that will always be executed even though <SAMP>do_put()</SAMP> will be overridden (this is the same strategy used in the design of the standard facets). In this base class, <SAMP>do_put()</SAMP> could be implemented to construct phone numbers in a generic international fashion, e.g., "+49-89-636-48018". </P>
<A NAME="2652"><H3>26.5.2 Adding Country Codes</H3></A>
<A NAME="idx596"><!></A>
<P>Let us now deal with the problem of adding the international country codes that were omitted from the previous class declaration. These country codes can be held as a map of strings that associates the country code with a mnemonic for the country's name, as shown in <A HREF="8-2.html#Table&nbsp;14">Table&nbsp;14</A>:</P>
<A NAME="idx597"><!></A>
<H4><A NAME="Figure&nbsp;14">Figure&nbsp;14: Map associating country codes with mnemonics for countries' names</A></H4>
<P><IMG SRC="images/stdlibug-Locales12.gif" WIDTH=560 HEIGHT=206></P>
<A NAME="idx598"><!></A>
<P>In the following code, we add the table of country codes:</P>
<UL><PRE>
class phone_put: public std::locale::facet {
public:
...
class CodeMap
: public std::map&lt;std::string, std::string&gt; { // 1
public:
CodeMap() {
insert (std::make_pair ("De", "49"));
insert (std::make_pair ("Fr", "33"));
insert (std::make_pair ("US", "1"));
...
}
};
static const CodeMap* getStdCodes () { // 2
return &amp;_stdCodes;
}
protected:
...
static CodeMap _stdCodes; // 3
};
</PRE></UL>
<P>Since the table of country codes is a constant table that is valid for all telephone number facet objects, it is added as a static data member _<SAMP>stdCodes</SAMP> (see <SAMP>//3</SAMP>). The initialization of this data member is encapsulated in a class, <SAMP>CodeMap</SAMP> (see <SAMP>//1</SAMP>). For convenience, a function <SAMP>getStdCodes()</SAMP> is added to give access to the table (see <SAMP>//2</SAMP>).</P>
<P>Despite its appealing simplicity, however, having just one static country code table might prove too inflexible. Consider that mnemonics might vary from one locale to another due to different languages. Maybe mnemonics are not called for, and you really need more extended names associated with the actual country code.</P>
<P>In order to provide more flexibility, we can build in the ability to work with an arbitrary table. A pointer to the respective country code table can be provided when a facet object is constructed. The static table, shown in <A HREF="26-5.html#Figure&nbsp;15">Figure&nbsp;15</A> below, serves as a default:</P>
<A NAME="idx599"><!></A>
<H4><A NAME="Figure&nbsp;15">Figure&nbsp;15: Map associating country codes with country names</A></H4>
<P><IMG SRC="images/stdlibug-Locales13.gif" WIDTH=552 HEIGHT=209></P>
<A NAME="idx600"><!></A>
<P>Since we hold the table as a pointer, we need to pay attention to memory management for the table pointed to. We use a flag for determining whether the provided table needs to be deleted when the facet is destroyed. The following code demonstrates use of the table and its associated flag:</P>
<UL><PRE>
class phone_put: public std::locale::facet {
public:
phone_put (size_t refs = 0)
: std::locale::facet (refs), _codeMap (&amp;_stdCodes),
_delete_it (false) {}
protected:
phone_put (const string_type &amp;cntryName, // 1
const string_type &amp;intlPrefix,
const CodeMap* codeMap = 0,
bool delete_it = false,
size_t refs = 0)
: std::locale::facet (refs), _cntryName (cntryName),
_intlPrefix (intlPrefix), _codeMap (codeMap),
_delete_it (delete_it)
{
if (!codeMap) // 2
_codeMap = &amp;_stdCodes;
}
const CodeMap* getCodes () { // 3
return _codeMap;
}
public:
virtual ~phone_put () {
if (_delete_it)
delete _codeMap; // 4
}
...
protected:
bool _delete_it;
const CodeMap* _codeMap;
static CodeMap _stdCodes; // 5
...
};
</PRE></UL>
<TABLE CELLPADDING="3">
<TR VALIGN="top"><TD><SAMP>//1</SAMP></TD><TD>The constructor is enhanced to take a pointer to the country code table, together with the flag for memory management of the provided table.
<TR VALIGN="top"><TD><SAMP>//2</SAMP></TD><TD>If no table is provided, the static table is installed as a default.
<TR VALIGN="top"><TD><SAMP>//3</SAMP></TD><TD>For convenience, a function that returns a pointer to the current table is added.
<TR VALIGN="top"><TD><SAMP>//4</SAMP></TD><TD>The table is deleted if the memory management flags says so.
<TR VALIGN="top"><TD><SAMP>//5</SAMP></TD><TD>Protected data members are added to hold the pointer to the current country code table, as well as the associated memory management flag.
</TABLE>
<BR>
<HR>
<A HREF="26-4.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-6.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

View File

@@ -0,0 +1,56 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright
ownership. The ASF licenses this file to you under the Apache
License, Version 2.0 (the License); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
Copyright 1999-2007 Rogue Wave Software, Inc.
-->
<HTML>
<HEAD>
<TITLE>An Example of a Derived Facet Class</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Apache stdcxx Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="26-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-7.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Apache C++ Standard Library User's Guide</B></DIV>
<H2>26.6 An Example of a Derived Facet Class</H2>
<A NAME="idx601"><!></A>
<P>As mentioned previously, the phone _put facet class is intended to serve as a base class. The facet does not format phone numbers in a locale-specific fasion.. Let's now present an example of a derived facet class, the US phone number formatting facet. This facet initializes the base class with the string "US" and its own locality, and the prefix for dialing foreign numbers, "011"; it works by default with the static country code table. Here is the class declaration for the facet:</P>
<UL><PRE>
class US_phone_put : public phone_put {
public:
US_phone_put (CodeMap* codeMap = 0, bool delete_it = false,
std::size_t refs = 0)
: phone_put ("US", "011", codeMap, delete_it, refs) { }
};
</PRE></UL>
<P>Other concrete facet classes are built similarly.</P>
<BR>
<HR>
<A HREF="26-5.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="26-7.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A>
<!-- Google Analytics tracking code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1775151-1";
urchinTracker();
</script>
<!-- end of Google Analytics tracking code -->
</BODY>
</HTML>

Some files were not shown because too many files have changed in this diff Show More