[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Set algorithms Up: The Standard Library Previous: valarray

Algorithms

Algorithms (in <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 Algorithms usually take as their first 2 arguments iterators to mark the range of elements to be operated on. For example, to replace 'A' by 'B' in a string str one could do
  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.


next up previous contents
Next: Set algorithms Up: The Standard Library Previous: valarray
Tim Love
2001-07-05