1. Trang chủ
  2. » Công Nghệ Thông Tin

C++ Primer Plus (P69) pps

20 178 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 56,63 KB

Nội dung

The erase() methods remove characters from a string. Here are the prototypes: basic_string& erase(size_type pos = 0, size_type n = npos); iterator erase(iterator position); iterator erase(iterator first, iterator last); The first form removes the character from position pos to n characters later, or the end of the string, whichever comes first. The second removes the single character referenced by the iterator position and returns an iterator to the next element, or, if there are no more elements, returns end(). The third removes the characters in the range [first, last); that is, including first and up to but not including last). The method returns an iterator to the element following the last element erased. Replacement Methods The various replace() methods identify part of a string to be replaced and identify the replacement. The part to be replaced can be identified by an initial position and a character count or by an iterator range. The replacement can be a string object, a string array, or a particular character duplicated several times. Replacement string objects and arrays can further be modified by indicating a particular portion, using a position and a count, just a count, or an iterator range. basic_string& replace(size_type pos1, size_type n1, const basic_string& str); basic_string& replace(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2); basic_string& replace(size_type pos, size_type n1, const charT* s, size_type n2); basic_string& replace(size_type pos, size_type n1, const charT* s); basic_string& replace(size_type pos, size_type n1, size_type n2, charT c); basic_string& replace(iterator i1, iterator i2, const basic_string& str); basic_string& replace(iterator i1, iterator i2, const charT* s, size_type n); basic_string& replace(iterator i1, iterator i2, const charT* s); basic_string& replace(iterator i1, iterator i2, size_type n, charT c); template<class InputIterator> basic_string& replace(iterator i1, iterator i2, This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. InputIterator j1, InputIterator j2); Here is an example: string test("Take a right turn at Main Street."); test.replace(7,5,"left"); // replace right with left Other Modifying Methods: copy() and swap() The copy() method copies a string object, or part thereof, to a designated string array: size_type copy(charT* s, size_type n, size_type pos = 0) const; Here s points to the destination array, n indicates the number of characters to copy, and pos indicates the position in the string object from which copying begins. Copying proceeds for n characters or until the last character in the string object, whichever comes first. The function returns the number of characters copied. The method does not append a null character, and it is up to the programmer to see that the array is large enough to hold the copy. Caution The copy() method does not append a null character nor does it check that the destination array is large enough. The swap() method swaps the contents of two string objects using a constant time algorithm: void swap(basic_string<charT,traits,Allocator>&); Output and Input The string class overloads the << operator to display string objects. It returns a reference to the istream object so that output can be concatenated: This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. string claim("The string class has many features."); cout << claim << endl; The string class overloads the >> operator so that you can read input into a string: string who; cin >> who; Input terminates on end-of-file, reading the maximum number of characters allowed in a string, or on reaching a whitespace character. (The definition of whitespace will depend on the character set and upon the type charT represents.) There are two getline() functions. The first has this prototype: template<class charT, class traits, class Allocator> basic_istream<charT,traits>& getline(basic_istream<charT,traits>& is, basic_string<charT,traits,Allocator>& str, charT delim); It reads characters from the input stream is into the string str until encountering the delim delimiter character, reaching the maximum size of the string, or encountering end-of-file. The delim character is read (removed from the input stream), but not stored. The second version lacks the third argument and uses the newline character (or its generalization) instead of delim: string str1, str2; getline(cin, str1); // read to end-of-line getline(cin, str2, '.'); // read to period CONTENTS This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. CONTENTS Appendix G. THE STL METHODS AND FUNCTIONS Members Common to All Containers Additional Members for Vectors, Lists, and Deques Additional Members for Sets and Maps STL Functions The STL aims to provide efficient implementations of common algorithms. It expresses these algorithms in general functions that can be used with any container satisfying the requirements for the particular algorithm and in methods that can be used with instantiations of particular container classes. This appendix assumes that you have some familiarity with the STL, such as might be gained from reading Chapter 16, "The string Class and the Standard Template Library." For example, this chapter assumes you know about iterators and constructors. Members Common to All Containers All containers define the types in Table G.1. In this table, X is a container type, such as vector<int>, and T is the type stored in the container, such as int. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. Table G.1. Types Defined for All Containers Type Value X::value_typeT, the element type X::referenceBehaves like T & X::const_referenceBehaves like const T & X::iteratorIterator type pointing to T, behaves like T * X::const_iteratorIterator type pointing to const T, behaves like const T * X::difference_typeSigned integral type used to represent the distance from one iterator to another; for example, the difference between two pointers X::size_typeUnsigned integral type size_type can represent size of data objects, number of elements, and subscripts The class definition will use a typedef to define these members. You can use these types, to declare suitable variables. For example, the following takes a roundabout way to replace the first occurrence of "bonus" in a vector of string objects with "bogus" in order to show how you can use member types to declare variables. vector<string> input; string temp; while (cin >> temp && temp != "quit") input.push_back(temp); vector<string>::iterator want= find(input.begin(), input.end(), string("bonus")); if (want != input.end()) { vector<string>::reference r = *want; r = "bogus"; } This code makes r a reference to the element in input to which want points. These types also can be used in more general code in which the type of container and element are generic. For example, suppose you want a min() function that takes as its argument a reference to a container and returns the smallest item in the container. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. This assumes that the < operator is defined for the value type and that you don't want to use the STL min_element() algorithm, which uses an iterator interface. Because the argument could be vector<int> or list<string> or deque<double>, use a template with a template parameter, such as Bag, to represent the container. So the argument type for the function will be const Bag & b. What about the return type? It should be the value type for the container, that is, Bag::value_type. However, at this point, Bag is just a template parameter, and the compiler has no way of knowing that the value_type member is actually a type. But you can use the typename keyword to clarify that a class member is a typedef: vector<string>::value_type st; // vector<string> a defined class typename Bag::value_type m; // Bag an as yet undefined type For the first definition, the compiler has access to the vector template definition, which states that value_type is a typedef. For the second definition, the typename keyword promises that the combination Bag::value_type is a typedef. These considerations lead to the following definition: template<typename Bag> typename Bag::value_type min(const Bag & b) { typename Bag::const_iterator it; typename Bag::value_type m = *b.begin(); for (it = b.begin(); it != b.end(); ++it) if (*it < m) m = *it; return m; } You then could use this template function as follows: vector<int> temperatures; // input temperature values into the vector int coldest = min(temperatures); The temperatures parameter would cause Bag to be evaluated as vector<int> and typename Bag::value_type to be evaluated as int. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. All containers also contain the member functions or operations listed in Table G.2. Again, X is a container type, such as vector<int>, and T is the type stored in the container, such as int. Also, a and b are values of type X. Table G.2. Methods Defined for All Containers Method/Operation Description begin()Returns an iterator to the first element end()Returns an iterator to past-the-end rbegin()Returns a reverse iterator to past-the-end rend()Returns a reverse iterator to first element size()Returns number of elements maxsize()Returns the size of the largest possible container empty()Returns true if the container is empty swap()Swaps the contents of two containers ==Returns true if two containers are the same size and have the same elements in the same order !=a != b is the same as !(a == b) <Returns true if a lexicographically precedes b > operator>>a > b is the same as b < a <=a <= b is the same as !(a > b) >== operator>=>a >= b is the same as !(a < b) The > operator for a container assumes that the > operator is defined for the value type. A lexicographical comparison is a generalization of alphabetical sorting. It compares two containers element by element until encountering an element in one container that doesn't equal the corresponding element in the other container. In that case, the containers are considered to be in the same order as the non-corresponding pair of elements. For example, if two containers are identical through the first ten elements, but the eleventh element in the first container is less than the eleventh element in the second container, the first container precedes the second. If two containers compare equal until one runs out of elements, the shorter container precedes the longer. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. Additional Members for Vectors, Lists, and Deques Vectors, lists, and deques are all sequences, and they all have the methods listed in Table G.3. Again, X is a container type, such as vector<int>, and T is the type stored in the container, such as int, a is a value of type X, t is a value of type X::value_type, i and j are input iterators, q2 and p are iterators, q and q1 are dereferenceable iterators (you can apply the * operator to them), and n is an integer of X::size_type. Table G.3. Methods Defined for Vectors, Lists, and Deques Method Description a.insert(p,t)Inserts a copy of t before p; returns an iterator pointing to the inserted copy of t. The default value for t is T(), that is, the value used for type T in the absence of explicit initialization. a.insert(p,n,t)Inserts n copies of t before p; no return value. a.insert(p,i,j)Inserts copies of the elements in range [i,j) before p, no return value. a.resize(n,t)If n > a.size(), inserts n - a.size() copies of t before a.end(); t has a default value of T(), that is, the value used for type T in the absence of explicit initialization. If n < a.size(), the elements following the nth element are erased. a.assign(i,j)Replaces the current contents of a with copies of the elements in range [i,j). a.assign(n,t)Replaces the current contents of a with n copies of t. The default value for t is T(),the value used for type T in the absence of explicit initialization. a.erase(q)Erases the element pointed to by q; returns an iterator to the element that had followed q. a.erase(q1,q2)Erases the elements in the range [q1,q2); returns an iterator pointing to the element q2 originally pointed to. a.clear()Same as erase(a.begin(), a.end()). a.front()Returns *a.begin() (the first element). a.back()Returns * a.end() (the last element). a.push_back(t)Inserts t before a.end(). a.pop_back()Erases the last element. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. Table G.4 lists methods common to two out of the three sequence classes. Table G.4. Methods Defined for Some Sequences Method Description Container a.push_front(t)Inserts a copy of t before the first element.list, deque a.pop_front()Erases the first element.list, deque a[n]Returns *(a.begin() + n). vector, deque a.at(n)Returns *(a.begin() + n), throws out_of_range exception if n > a.size(). vector, deque The vector template additionally has the methods in Table G.5. Here, a is a vector container and n is an integer of X::size_type. Table G.5. Additional Methods for Vectors Method Description a.capacity() Returns the total number of elements the vector can hold without requiring reallocation. a.reserve(n) Alerts object a that memory for at least n elements is needed. After the method call, the capacity will be at least n elements. Reallocation occurs if n is greater than the current capacity. If n is greater than a.max_size(), the method throws a length_error exception. The list template additionally has the methods in Table G.6. Here, a and b are list containers, and T is the type stored in the list, such as int, t is a value of type T, i and j are input iterators, q2 and p are iterators, q and q1 are dereferenceable iterators, and n is an integer of X::size_type. The table uses the standard STL notation of [i, j) meaning the range from i up to, but not including j. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. Table G.6. Additional Methods for Lists Method Description a.splice(p,b)Moves the contents of list b to list a, inserting them before p. a.splice(p,b,i)Moves the element in list b pointed to by i to before position p in list a. a.splice(p,b,i,j)Moves the elements in range [i,j) of list b to before position p in list a. a.remove(const T& t)Erases all elements in list a having the value t. a.remove_if(Predicate pred) Given that i is an iterator into the list a, erases all values for which pred(*i) is true. (A Predicate is a Boolean function or function object, as discussed in Chapter 15, "Friends, Exceptions, and More.") a.unique()Erases all but the first element from each group of consecutive equal elements. a.unique(BinaryPredicate bin_pred) Erases all but the first element from each group of consecutive elements for which bin_pred(*i, * (i - 1)) is true. (A BinaryPredicate is a Boolean function or function object, as discussed in Chapter 15.) a.merge(b)Merges the contents of list b with list a using the < operator defined for the value type. If an element in a is equivalent to an element in b, the element from a is placed first. List b is empty after the merge. a.merge(b, Compare comp) Merges the contents of list b with list a using the comp function or function object. If an element in a is equivalent to an element in b, the element from a is placed first. List b is empty after the merge. a.sort()Sorts list a using the < operator. a.sort(Compare comp)Sorts list a using the comp function or function object. a.reverse()Reverses the order of the elements in list a. Additional Members for Sets and Maps This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks.

Ngày đăng: 07/07/2014, 06:20

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN