New STL Algorithms That Will Make A More Productive Developer
IntroductionC++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 AlgorithmsThe classic copy algorithms, e.g.,
#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
#include <algorithm>
const int n=4;
int first[n]={0,1,2,3};
int result[n];
uninitialized_copy_n(first, n, result);
Finally,
#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 ofThe Standard Library now defines algorithms that mimic the set theory operations
The following examples apply the predicate
#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
PartitionA range whose elements that satisfy a certain predicate precede the elements that fail to satisfy it is a partition. C++03 defines the
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()));
IotaThe 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 ++.
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'}
ConclusionTechnically 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 |