New STL Algorithms That Will Make A More Productive Developer

 

Introduction

C++0x was recently furnished with new algorithms. Some of them fill in gaps in the C++03 Standard Library whereas others are convenience algorithms that simplify recurrent programming tasks by using more intuitive parameter lists and a cleaner interface. In the following sections I will demonstrate 10 such algorithms, all of which save one are brand new.

New Copy Algorithms

The classic copy algorithms, e.g., copy()uninitialized_copy() etc., take two iterators indicating the beginning and the end of a range, and a single output iterator marking the beginning of the output range. However, in many programming tasks, it's more convenient to define the copy operation by specifying a starting point and a count instead of using starting and ending points. C++0x introduces a new family of copy_n() algorithms that copy nelements. Suppose you want to copy an array of 5 elements to another array. Using copy_n(), it's simple:

 

  #include <algorithm>
  int source[5]={0,12,34,50,80};
  int target[5];
  //copy 5 elements from source to target
  copy_n(source,5,target);

 

 

C++0x also provides a new version of uninitialized_copy() that takes a count. uninitialized_copy_n() is chiefly useful in low-level memory management operations where you want to separate the allocation of raw memory from the construction operation. The following uninitialized_copy_n() call copies a POD array to another array:

 

  #include <algorithm>
  const int n=4;
  int first[n]={0,1,2,3};
  int result[n];
  uninitialized_copy_n(first, n, result);

 

Finally, copy_if() is a new convenience algorithm that selectively copies every element that satisfies the predicate p within the range [first,last). In the following example, copy_if() copies only the positive numbers from the range [first, last) to result:

 

  #include <algorithm>
  struct ispositive //predicate
  {
   bool operator()(int val) const {return val>=0;}
  };
  int first[n]={0,-1,-2,3};
  int result[n]={0};
  copy_if(first, first+n, result, ispositive());

 

All of, Any of and None of

The Standard Library now defines algorithms that mimic the set theory operations all_of()any_of() and none_of(). Given a range and a predicate p, the algorithm determines whether p is true for:

 

  1. All of the elements within the range (all_of()).
  2. At least one element within the range (any_of()).
  3. No elements within the range (none_of()).

 

The following examples apply the predicate ispositive() to the range [first, first+n) and uses all_of()any_of() and none_of() to examine the range's properties:

 

  #include <algorithm>
  //are all of the elements positive?
  all_of(first, first+n, ispositive()); //false
  //is there at least one positive element?
  any_of(first, first+n, ispositive());//true
  // are none of the elements positive?
  none_of(first, first+n, ispositive()); //false

 

Partition

A range whose elements that satisfy a certain predicate precede the elements that fail to satisfy it is a partition. C++03 defines the partition()algorithms for partitioning a range. C++0x introduced the new algorithm is_partitioned() that examines whether a given range makes a valid partition. The following listing examines whether a given range is a partition. If it's not, it calls partition() and examines the range again:

 

   if(!is_partitioned(first, first+n, ispositive())); 
     partition(first, first+n, ispositive()); 
   bool b=
     is_partitioned(first, first+n, ispositive());//now true
   
   To detect the partition point in a partitioned range, use the new algorithm partition_point(). partition_point() returns an iterator to the first element that doesn't satisfy the specified predicate:
   
   int firstnegative=
    *(partition_point(first, first+n, ispositive()));

Iota

The new algorithm iota() was inspired by an APL operator with the same name. iota() creates a range of sequentially increasing values, as if by assigning an initial value to *first, then incrementing that value using prefix ++. iota() takes two iterators marking a range, and an initial value. This algorithm is particularly useful for testing since permutations of {1, 2,...N} are frequently used as test input. In the following example, iota() assigns the consecutive values {10,11,12,13,14} to the array arr, and {'a', 'b', 'c'} to the char array c. Notice that you need to #include <numeric> to use iota():

 

  include <numeric>
  int a[5]={0};
  char c[3]={0};
  iota(a, a+5, 10); //changes a to {10,11,12,13,14}
  iota(c, c+3, 'a'); //{'a','b','c'}

 

Conclusion

Technically speaking, some of the algorithms that I've presented seem redundant since you can achieve the same result by using a different algorithm and a different list of arguments. For example, copy_if() is the inverse of remove_copy_if(). That is, copying all elements that satisfy a predicate p is the same as not copying all elements that satisfy !p. However, it's more convenient and certainly less confusing to use copy_if() directly. A complete list of the new Standard Library algorithms is available here. With respect to vendors' support, Microsoft's Visual Studio 2010 already supports all of the algorithms exemplified above. Other implementations support these algorithms partially so you should check the documentation of your implementation's Standard Library.

posted @ 2012-04-06 21:57  worldworld  阅读(321)  评论(0编辑  收藏  举报