Generic Algorithms

Generic Algorithms

We’ve already seen one generic algorithm: reverse().

find()

Another generic algorithm is find().

Here’s an example using a regular array of chars:

//
//  FindExample.cpp
//  STL Sequence Containers
//
//  Created by Bryan Higgs on 10/20/24.
//

#include <iostream>
#include <algorithm>  // For find()

int main(int argc, const char * argv[])
{
  char s[] = "Example of generic find algorithm";
  size_t len = strlen(s);
  const char *foundChar = std::find(&s[0], &s[len], 'g');
  std::cout << "Found character: " << *foundChar << std::endl
            << "Next character: " << *(foundChar+1) << std::endl;
  
  return 0;
}

… which outputs:

Found character: g
Next character: e
Program ended with exit code: 0

Here’s how you can use find() with a std::vector :

//
//  FindExample2.cpp
//  STL Sequence Containers
//
//  Created by Bryan Higgs on 10/20/24.
//

#include <iostream>
#include <vector>  // For vector
#include <algorithm>  // For find()

#include "Make.h"

int main(int argc, const char * argv[])
{
  std::vector<char> v = make< std::vector<char> >(
        "Example of generic find algorithm");
  std::vector<char>::iterator foundChar
        = find(v.begin(), v.end(), 'g');
  std::cout << "Found character: " << *foundChar << std::endl
            << "Next character: " << *(foundChar+1) << std::endl;

  return 0;
}

… which outputs the exact same thing as the previous example:

Found character: g
Next character: e
Program ended with exit code: 0

merge()

Another generic algorithm from the STL is merge(), which combines the contents of two sorted sequences into a single sorted sequence:

//
//  MergeExample.cpp
//  STL Sequence Containers
//
//  Created by Bryan Higgs on 10/20/24.
//

#include <iostream>
#include <list>     // For list
#include <deque>    // For deque
#include <algorithm>// For merge

#include "make.h"

int main(int argc, const char * argv[])
{
  char vowels[] = "aeiou";
  size_t len = strlen(vowels);
  std::cout << "Vowels: " << vowels << std::endl;
  
  std::list<char> consonants
    = make< std::list<char> >("bcdfghjklmnpqrstvwxyz");
  std::cout << "Consonants: ";
  for (char c: consonants)
  {
    std::cout << c;
  }
  std::cout << std::endl;
  
  std::deque<char> letters(26, 'X');
  std::cout << "Letters (initial) : ";
  for (char c: letters)
  {
    std::cout << c;
  }
  std::cout << std::endl;
  
  merge(&vowels[0], &vowels[len],
        consonants.begin(), consonants.end(),
        letters.begin()
        );
  std::cout << "Letters (final) : ";
  for (char c: letters)
  {
    std::cout << c;
  }
  std::cout << std::endl;
  
  return 0;
}

… which outputs the exact same thing as the previous example:

Vowels: aeiou
Consonants: bcdfghjklmnpqrstvwxyz
Letters (initial) : XXXXXXXXXXXXXXXXXXXXXXXXXX
Letters (final) : abcdefghijklmnopqrstuvwxyz
Program ended with exit code: 0
Index