Abstract
If you want to replace the iterator In the iner with another value, the container does not provide the Replace () member function, but provides the Replace () function () this generic algorithm.
Introduction
In the following example, we replace all 1 in the vector with 4.
1 /**/ /*
2 (C) oomusou 2006 Http://oomusou.cnblogs.com
3
4 Filename: genericalgo_replace.cpp
5 Compiler: Visual C + + 8.0/iso c ++
6 Description: Demo how to use Replace () Algorithm
7 Release: 04/19/2006 1.0
8 */
9 # Include < Iostream >
10 # Include < Vector >
11 # Include < Algorithm >
12 # Include < Sstream >
13
14 Using Namespace STD;
15
16 Int Main () {
17 Int IA [] = {1,2,3} ;
18 Vector < Int > Ivec (IA, IA + Sizeof (Ia) / Sizeof ( Int ));
19 Replace (ivec. Begin (), ivec. End (), 1 , 4 );
20
21 Copy (ivec. Begin (), ivec. End (), ostream_iterator < Int > (Cout, " \ N " ));
22 }
Results
4
2
3
19 rows
Replace (ivec. Begin (), ivec. End (), 1 , 4 );
The first vertex is the starting address of the vector, the second vertex is the end address of the vector, and the third vertex is the value to be replaced, the fourth percentile is the value to be replaced.
The complete definition of Replace () is as follows:
Template < Typename forwarditerator, typename t >
Void Replace (forwarditerator first, forwarditerator last, Const T & Old_value, Const T & New_value );
Other related algorithm also includes replace_if (), replace_copy (), replace_copy_if ().
Conclusion
Beginners learn STL, which is difficult to understand due to the limited functionality provided by STL container containers, because STL is a product based on generic (GP: Generic programming, and objects.. NET Framework and Java SDK are different. When the object goes down, Algorithm and container are combined, and each container provides its own algorithm (member function) for self-sufficiency. However, many iner must provide the same basic functions, which will cause the class to become very fat and duplicate the same functions. For example, vector must provide Replace (), how can list, deque, and stack be implemented? Do I need to reset Replace () again? Generic ‑distributed relational algorithm and container are classified, while algorithm supports various iner types. For developers who develop STL, only one replace () can be developed, for STL users, you only need to learn how to replace () once, and to change from vector to list in the future, you only need to delete the container, other programs do not need to be modified.
So when using STL, if the container does not provide the compile function, don't forget to look for generic algorithm, you can also appreciate the beauty of the library under GP thinking.