![[Dept of Engineering]](http://www.eng.cam.ac.uk/images/house_style/engban-s.gif)
<algorithm>) operate on containers, including
strings. They may
not always be the fastest option but they're often the easiest.
They fall into 6 groups
search(), count_if(), etc.
sort(), merge(), etc.
remove(), unique(), etc.
partial_sum(), inner_product(), etc.
generate(), for_each(), etc.
equal(), min(), etc.
replace(str.begin(), str.end(), 'A', 'B');
Here's one way to count how many instances of a particular character there are in a string using the find algorithm.
int count (const string& s, char c)
{
string::const_iterator i=find(s.begin(), s.end(),c);
int n=0;
while(i!=s.end()){
++n;
i=find(i+1, s.end(),c);
}
return n;
}
Here's a way to count the number of 'z' characters in a C-style string using the count algorithm. Note how the character array can be used like other containers.
void g(char cs[], int sz)
{
int i1 = count(&cs[0], &cs[sz], 'z');
}
Here's the count algorithm again, this time being used to find a particular complex number in a list.
void f(list<complex>&lc)
{
int i1 = count(lc.begin(), lc.end(), complex(1,3));
}
Other algorithms include next_permutation and prev_permutation
int main()
{
char v[]="abcd";
cout << v << '\t';
while (next_permutation(v, v+4))
cout << v << '\t';
}
random_shuffle,
char v[]="abcd";
cout << v << '\t';
for (int i=5;i;i--) {
random_shuffle(v, v+4);
cout << v << '\t';
}
and a routine to cycle elements
rotate (first, middle, last)
rotate ``swaps" the segment that contains elements from first through middle-1 with the segment that contains the elements from middle through last.